{"id":2704,"date":"2026-02-05T10:55:04","date_gmt":"2026-02-05T10:55:04","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2704"},"modified":"2026-02-05T10:55:04","modified_gmt":"2026-02-05T10:55:04","slug":"chapter-59-swift-nested-loops","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/chapter-59-swift-nested-loops\/","title":{"rendered":"Chapter 59: Swift Nested Loops"},"content":{"rendered":"<h3 dir=\"auto\">1. What is a nested loop? (very clear definition)<\/h3>\n<p dir=\"auto\">A <strong>nested loop<\/strong> means <strong>one loop inside another loop<\/strong>.<\/p>\n<p dir=\"auto\">The inner loop <strong>runs completely<\/strong> for <strong>every single iteration<\/strong> of the outer loop.<\/p>\n<p dir=\"auto\">Analogy that almost everyone understands:<\/p>\n<p dir=\"auto\">Think of a <strong>calendar<\/strong>:<\/p>\n<ul dir=\"auto\">\n<li>Outer loop = <strong>months<\/strong> (12 times)<\/li>\n<li>Inner loop = <strong>days<\/strong> in that month (28\u201331 times)<\/li>\n<\/ul>\n<p dir=\"auto\">For each month, you go through every day \u2192 total iterations = sum of days in each month.<\/p>\n<p dir=\"auto\">In code terms:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>for outer in something {        \/\/ runs 5 times\r\n    for inner in somethingElse { \/\/ runs 3 times for EACH outer iteration\r\n        print(\"outer:\\(outer), inner:\\(inner)\")\r\n    }\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Total prints: 5 \u00d7 3 = 15 times<\/p>\n<h3 dir=\"auto\">2. The classic first example \u2013 multiplication table<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>print(\"Multiplication Table (1 to 10)\")\r\nprint(\"-----------------------------\")\r\n\r\nfor row in 1...10 {\r\n    var line = \"\"\r\n    \r\n    for column in 1...10 {\r\n        let product = row * column\r\n        line += String(format: \"%4d\", product) + \" \"\r\n    }\r\n    \r\n    print(line)\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Output (partial):<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>text<\/div>\n<div>\n<pre tabindex=\"0\"><code>Multiplication Table (1 to 10)\r\n-----------------------------\r\n   1    2    3    4    5    6    7    8    9   10 \r\n   2    4    6    8   10   12   14   16   18   20 \r\n   3    6    9   12   15   18   21   24   27   30 \r\n...<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Why nested loops are natural here:<\/strong><\/p>\n<ul dir=\"auto\">\n<li>Outer loop = rows (which number we are multiplying)<\/li>\n<li>Inner loop = columns (1 \u00d7 row, 2 \u00d7 row, 3 \u00d7 row, \u2026)<\/li>\n<\/ul>\n<h3 dir=\"auto\">3. Real-life example 1 \u2013 Tic-tac-toe board (2D grid)<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>var board = [\r\n    [\" \", \" \", \" \"],\r\n    [\" \", \" \", \" \"],\r\n    [\" \", \" \", \" \"]\r\n]\r\n\r\n\/\/ Place some moves\r\nboard[0][0] = \"X\"\r\nboard[1][1] = \"O\"\r\nboard[2][2] = \"X\"\r\n\r\n\/\/ Print the board nicely\r\nprint(\"  0 1 2\")\r\nprint(\" -------\")\r\n\r\nfor rowIndex in 0..&lt;board.count {\r\n    print(\"\\(rowIndex)|\", terminator: \"\")\r\n    \r\n    for colIndex in 0..&lt;board[rowIndex].count {\r\n        let cell = board[rowIndex][colIndex]\r\n        print(\" \\(cell) \", terminator: \"\")\r\n        \r\n        if colIndex &lt; board[rowIndex].count - 1 {\r\n            print(\"|\", terminator: \"\")\r\n        }\r\n    }\r\n    \r\n    print()\r\n    \r\n    if rowIndex &lt; board.count - 1 {\r\n        print(\" -------\")\r\n    }\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Output:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>text<\/div>\n<div>\n<pre tabindex=\"0\"><code>0 1 2\r\n -------\r\n0| X |   |   \r\n -------\r\n1|   | O |   \r\n -------\r\n2|   |   | X<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Key learning points:<\/strong><\/p>\n<ul dir=\"auto\">\n<li>Outer loop = rows<\/li>\n<li>Inner loop = columns inside each row<\/li>\n<li>We use two indices: rowIndex and colIndex<\/li>\n<\/ul>\n<h3 dir=\"auto\">4. Real-life example 2 \u2013 Seating arrangement \/ table plan<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let tables = [\r\n    [\"Rahul\", \"Priya\", \"Aarav\"],\r\n    [\"Sneha\", \"Karan\", \"Meera\", \"Vikram\"],\r\n    [\"Ananya\", \"Rohan\"]\r\n]\r\n\r\nprint(\"Wedding Table Seating\")\r\nprint(\"=====================\")\r\n\r\nfor tableNumber in 0..&lt;tables.count {\r\n    print(\"Table \\(tableNumber + 1):\")\r\n    \r\n    for (seat, guest) in tables[tableNumber].enumerated() {\r\n        print(\"  Seat \\(seat + 1): \\(guest)\")\r\n    }\r\n    \r\n    print()\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Output:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>text<\/div>\n<div>\n<pre tabindex=\"0\"><code>Wedding Table Seating\r\n=====================\r\nTable 1:\r\n  Seat 1: Rahul\r\n  Seat 2: Priya\r\n  Seat 3: Aarav\r\n\r\nTable 2:\r\n  Seat 1: Sneha\r\n  Seat 2: Karan\r\n  Seat 3: Meera\r\n  Seat 4: Vikram\r\n\r\nTable 3:\r\n  Seat 1: Ananya\r\n  Seat 2: Rohan<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Typical pattern<\/strong>:<\/p>\n<ul dir=\"auto\">\n<li>Outer loop = tables \/ groups \/ categories<\/li>\n<li>Inner loop = people \/ items \/ sub-items inside each group<\/li>\n<\/ul>\n<h3 dir=\"auto\">5. Real-life example 3 \u2013 Search \/ filter in 2D data<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let students = [\r\n    [\"Rahul\",   \"A\", 92],\r\n    [\"Priya\",   \"A\", 98],\r\n    [\"Aarav\",   \"B\", 85],\r\n    [\"Sneha\",   \"A+\", 95],\r\n    [\"Karan\",   \"C\", 68]\r\n]\r\n\r\nprint(\"Students who scored 90+:\")\r\n\r\nfor student in students {\r\n    let name = student[0] as! String\r\n    let grade = student[1] as! String\r\n    let marks = student[2] as! Int\r\n    \r\n    if marks &gt;= 90 {\r\n        print(\"  \u2022 \\(name) \u2013 \\(grade) (\\(marks)%)\")\r\n    }\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Output:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>text<\/div>\n<div>\n<pre tabindex=\"0\"><code>Students who scored 90+:\r\n  \u2022 Priya \u2013 A (98%)\r\n  \u2022 Sneha \u2013 A+ (95%)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">6. Real-life example 4 \u2013 Pattern printing (great for understanding nesting)<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let size = 5\r\n\r\nfor row in 1...size {\r\n    for _ in 1...row {\r\n        print(\"*\", terminator: \"\")\r\n    }\r\n    print()\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Output:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>text<\/div>\n<div>\n<pre tabindex=\"0\"><code>*\r\n**\r\n***\r\n****\r\n*****<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Reverse pattern<\/strong>:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>for row in 1...size {\r\n    \/\/ spaces first\r\n    for _ in 1...(size - row) {\r\n        print(\" \", terminator: \"\")\r\n    }\r\n    \r\n    \/\/ stars\r\n    for _ in 1...row {\r\n        print(\"*\", terminator: \"\")\r\n    }\r\n    \r\n    print()\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Output:<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>text<\/div>\n<div>\n<pre tabindex=\"0\"><code>*\r\n   **\r\n  ***\r\n ****\r\n*****<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">7. Very Common Beginner Mistakes &amp; How to Avoid Them<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"lg\">Mistake<\/th>\n<th data-col-size=\"md\">Wrong \/ Dangerous code<\/th>\n<th data-col-size=\"lg\">Correct \/ Better habit<\/th>\n<th data-col-size=\"lg\">Why?<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"lg\">Modifying outer collection inside inner loop<\/td>\n<td data-col-size=\"md\">for row in grid { for cell in row { grid.append(\u2026) } }<\/td>\n<td data-col-size=\"lg\">Build new collection or use indices<\/td>\n<td data-col-size=\"lg\">Collection mutated while being iterated \u2013 crash<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Forgetting to reset inner counter<\/td>\n<td data-col-size=\"md\">for i in 1&#8230;5 { for j in 1&#8230;5 { print(i,j) } } (but j not reset)<\/td>\n<td data-col-size=\"lg\">Each inner loop is independent<\/td>\n<td data-col-size=\"lg\">Inner loop resets automatically<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Using wrong index range<\/td>\n<td data-col-size=\"md\">for i in 0&#8230;rows { \u2026 }<\/td>\n<td data-col-size=\"lg\">for i in 0..&lt;rows { \u2026 }<\/td>\n<td data-col-size=\"lg\">0&#8230;rows.count tries to access out-of-bounds<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Deep nesting (pyramid of doom)<\/td>\n<td data-col-size=\"md\">5+ levels of nested for\/if<\/td>\n<td data-col-size=\"lg\">Extract to functions or flatten logic<\/td>\n<td data-col-size=\"lg\">Code becomes unreadable &amp; hard to debug<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Assuming all rows have same length<\/td>\n<td data-col-size=\"md\">matrix[row][col] without check<\/td>\n<td data-col-size=\"lg\">if col &lt; matrix[row].count { \u2026 }<\/td>\n<td data-col-size=\"lg\">Rows can have different lengths<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">8. Quick Reference \u2013 Most Used Nested Loop Patterns<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"sm\">Goal<\/th>\n<th data-col-size=\"xl\">Typical nested loop structure<\/th>\n<th data-col-size=\"lg\">Real-life feeling \/ use-case<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"sm\">Print 2D grid \/ table<\/td>\n<td data-col-size=\"xl\">for row in rows { for col in columns { \u2026 } }<\/td>\n<td data-col-size=\"lg\">Chessboard, calendar, spreadsheet view<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"sm\">Process rows &amp; columns independently<\/td>\n<td data-col-size=\"xl\">for row in matrix { for cell in row { \u2026 } }<\/td>\n<td data-col-size=\"lg\">Matrix math, image processing, game board<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"sm\">Numbered list inside groups<\/td>\n<td data-col-size=\"xl\">for group in groups { for (i, item) in group.enumerated() { \u2026 } }<\/td>\n<td data-col-size=\"lg\">Seating plan, grouped tasks, multi-team leaderboard<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"sm\">Pattern printing (stars, numbers, shapes)<\/td>\n<td data-col-size=\"xl\">for row in 1&#8230;n { for col in 1&#8230;row { print(&#8220;*&#8221;) } }<\/td>\n<td data-col-size=\"lg\">Understanding loops, interview questions<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"sm\">Search \/ filter in 2D data<\/td>\n<td data-col-size=\"xl\">for row in data { for item in row { if condition { \u2026 } } }<\/td>\n<td data-col-size=\"lg\">Find all matching cells, count occurrences<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">9. Small Practice \u2013 Try these<\/h3>\n<ol dir=\"auto\">\n<li><strong>Mini multiplication table<\/strong> (5\u00d75) Print 1\u00d71 to 5\u00d75 using nested for<\/li>\n<li><strong>Right-aligned triangle of stars<\/strong> For size = 5, print:<\/li>\n<\/ol>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>text<\/div>\n<div>\n<pre tabindex=\"0\"><code>*\r\n   **\r\n  ***\r\n ****\r\n*****<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<ol dir=\"auto\" start=\"3\">\n<li><strong>Print a 4\u00d76 grid of coordinates<\/strong> Output should look like:<\/li>\n<\/ol>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>text<\/div>\n<div>\n<pre tabindex=\"0\"><code>(0,0) (0,1) (0,2) (0,3) (0,4) (0,5)\r\n(1,0) (1,1) (1,2) (1,3) (1,4) (1,5)\r\n(2,0) (2,1) (2,2) (2,3) (2,4) (2,5)\r\n(3,0) (3,1) (3,2) (3,3) (3,4) (3,5)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Paste your code here if you want feedback or want to see cleaner \/ more elegant versions!<\/p>\n<p dir=\"auto\">What would you like to explore next?<\/p>\n<ul dir=\"auto\">\n<li>Nested loops with <strong>break<\/strong> and <strong>continue<\/strong><\/li>\n<li>Nested loops in <strong>SwiftUI<\/strong> (ForEach inside ForEach)<\/li>\n<li>How to <strong>flatten<\/strong> nested loops into functional style (flatMap, map + joined)<\/li>\n<li>Multidimensional arrays + nested loops (2D tables, grids\u2026)<\/li>\n<li>Or move to another topic (dictionaries, sets, optionals, switch\u2026)<\/li>\n<\/ul>\n<p dir=\"auto\">Just tell me \u2014 we\u2019ll continue in the same clear, patient, detailed style \ud83d\ude0a<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. What is a nested loop? (very clear definition) A nested loop means one loop inside another loop. The inner loop runs completely for every single iteration of the outer loop. Analogy that almost&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76],"tags":[],"class_list":["post-2704","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2704","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/comments?post=2704"}],"version-history":[{"count":1,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2704\/revisions"}],"predecessor-version":[{"id":2705,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2704\/revisions\/2705"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2704"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2704"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2704"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}