{"id":2702,"date":"2026-02-05T10:47:45","date_gmt":"2026-02-05T10:47:45","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2702"},"modified":"2026-02-05T10:47:45","modified_gmt":"2026-02-05T10:47:45","slug":"chapter-58-for-loop","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/chapter-58-for-loop\/","title":{"rendered":"Chapter 58: For Loop"},"content":{"rendered":"<h3 dir=\"auto\">1. Why do we need a for loop?<\/h3>\n<p dir=\"auto\">A for loop is the most natural way to say:<\/p>\n<blockquote dir=\"auto\">\n<p dir=\"auto\">\u201cPlease do this same thing <strong>once for every item<\/strong> in this list \/ collection \/ range.\u201d<\/p>\n<\/blockquote>\n<p dir=\"auto\">In everyday language:<\/p>\n<ul dir=\"auto\">\n<li>\u201cFor each fruit in my basket, print its name.\u201d<\/li>\n<li>\u201cFor every number from 1 to 10, add it to the total.\u201d<\/li>\n<li>\u201cFor each row in the table, show the student\u2019s name and score.\u201d<\/li>\n<\/ul>\n<p dir=\"auto\">Swift\u2019s for loop is <strong>very expressive<\/strong> and <strong>very safe<\/strong> compared to older languages \u2014 you almost never need to manually manage an index counter.<\/p>\n<h3 dir=\"auto\">2. The three most common forms of for (you will use these 95% of the time)<\/h3>\n<h4 dir=\"auto\">Form A \u2013 for item in collection (the most frequent style)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let fruits = [\"Mango\", \"Banana\", \"Apple\", \"Orange\", \"Guava\", \"Pineapple\"]\r\n\r\nfor fruit in fruits {\r\n    print(\"I love eating \\(fruit) \ud83c\udf4b\")\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>I love eating Mango \ud83c\udf4b\r\nI love eating Banana \ud83c\udf4b\r\nI love eating Apple \ud83c\udf4b\r\nI love eating Orange \ud83c\udf4b\r\nI love eating Guava \ud83c\udf4b\r\nI love eating Pineapple \ud83c\udf4b<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>When you use this style (almost always at first):<\/strong><\/p>\n<ul dir=\"auto\">\n<li>You only care about <strong>each element<\/strong> (the value)<\/li>\n<li>You <strong>don\u2019t<\/strong> need to know its position in the list<\/li>\n<li>You are doing something simple: print, process, add to another list, show in UI\u2026<\/li>\n<\/ul>\n<h4 dir=\"auto\">Form B \u2013 for (index, item) in collection.enumerated() (when you need the position)<\/h4>\n<p dir=\"auto\">This is the <strong>second most common<\/strong> form \u2014 you use it as soon as you need numbering or positioning.<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let fruits = [\"Mango\", \"Banana\", \"Apple\", \"Orange\"]\r\n\r\nfor (index, fruit) in fruits.enumerated() {\r\n    print(\"\\(index + 1). I love \\(fruit)\")\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>1. I love Mango\r\n2. I love Banana\r\n3. I love Apple\r\n4. I love Orange<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Typical real situations where you almost always use enumerated():<\/strong><\/p>\n<ul dir=\"auto\">\n<li>Showing numbered lists (tasks, search results, leaderboard, cart items)<\/li>\n<li>Creating numbered UI rows \/ cells<\/li>\n<li>Logging with line numbers<\/li>\n<li>Pairing items with their position in reports<\/li>\n<\/ul>\n<h4 dir=\"auto\">Form C \u2013 for number in range (when you want to count \/ repeat N times)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>\/\/ 0-based (most common for indices)\r\nfor i in 0..&lt;5 {\r\n    print(\"Round \\(i + 1)\")\r\n}\r\n\r\n\/\/ 1-based (very common in user messages \/ reports)\r\nfor level in 1...10 {\r\n    print(\"Level \\(level) unlocked!\")\r\n}\r\n\r\n\/\/ Backwards\r\nfor countdown in (1...5).reversed() {\r\n    print(\"\\(countdown)\u2026\")\r\n}\r\nprint(\"Blast off! \ud83d\ude80\")<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">3. Real-life examples \u2014 code you will actually write in apps<\/h3>\n<h4 dir=\"auto\">Example 1 \u2013 Numbered to-do list \/ task manager<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let tasks = [\r\n    \"Finish Swift lesson on loops\",\r\n    \"Buy vegetables &amp; milk\",\r\n    \"Call mom\",\r\n    \"Reply to pending emails\",\r\n    \"Gym \u2013 45 min cardio\"\r\n]\r\n\r\nprint(\"Today's To-Do List\")\r\nprint(\"-------------------\")\r\n\r\nfor (index, task) in tasks.enumerated() {\r\n    let status = index &lt; 2 ? \"\u2705 Done\" : \"\u23f3 Pending\"\r\n    print(\"  \\(index + 1). \\(task)   \\(status)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 2 \u2013 Shopping cart receipt (very common in e-commerce)<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>struct CartItem {\r\n    let name: String\r\n    let price: Double\r\n    let quantity: Int\r\n}\r\n\r\nlet cart = [\r\n    CartItem(name: \"Wireless Earbuds\", price: 3499, quantity: 1),\r\n    CartItem(name: \"Phone Case\",       price: 799,  quantity: 2),\r\n    CartItem(name: \"Screen Protector\", price: 499,  quantity: 1)\r\n]\r\n\r\nprint(\"Receipt\")\r\nprint(\"--------------------------------\")\r\n\r\nvar total: Double = 0\r\n\r\nfor (index, item) in cart.enumerated() {\r\n    let lineTotal = item.price * Double(item.quantity)\r\n    total += lineTotal\r\n    \r\n    print(\"\\(index + 1). \\(item.name) \u00d7 \\(item.quantity)\")\r\n    print(\"   \u20b9\\(String(format: \"%.2f\", item.price)) each \u2192 \u20b9\\(String(format: \"%.2f\", lineTotal))\")\r\n    print(\"---\")\r\n}\r\n\r\nprint(\"Grand Total: \u20b9\\(String(format: \"%.2f\", total))\")<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 3 \u2013 Progress checklist \/ onboarding steps<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let onboardingSteps = [\r\n    \"Create account\",\r\n    \"Verify email\",\r\n    \"Set up profile picture\",\r\n    \"Choose interests\",\r\n    \"Connect contacts (optional)\",\r\n    \"Start exploring!\"\r\n]\r\n\r\nprint(\"Onboarding Progress\")\r\nprint(\"-------------------\")\r\n\r\nfor (index, step) in onboardingSteps.enumerated() {\r\n    let isCompleted = index &lt; 3  \/\/ pretend first 3 are done\r\n    let mark = isCompleted ? \"\u2705\" : \"\u23f3\"\r\n    print(\"  \\(index + 1). \\(step)  \\(mark)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 4 \u2013 Print a simple multiplication table<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let number = 7\r\n\r\nprint(\"\\(number) \u00d7 Table\")\r\nprint(\"------------\")\r\n\r\nfor i in 1...10 {\r\n    let result = number * i\r\n    print(\"  \\(number) \u00d7 \\(i) = \\(result)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">4. 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=\"lg\">Wrong \/ Dangerous code<\/th>\n<th data-col-size=\"lg\">Correct \/ Better habit<\/th>\n<th data-col-size=\"md\">Why?<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"lg\">Using 1&#8230;count instead of 0..&lt;count<\/td>\n<td data-col-size=\"lg\">for i in 1&#8230;fruits.count { \u2026 }<\/td>\n<td data-col-size=\"lg\">for i in 0..&lt;fruits.count { \u2026 }<\/td>\n<td data-col-size=\"md\">Index 5 when count=5 \u2192 crash<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Force-unwrapping first \/ last<\/td>\n<td data-col-size=\"lg\">fruits.first!<\/td>\n<td data-col-size=\"lg\">fruits.first ?? &#8220;None&#8221; or if let first = fruits.first<\/td>\n<td data-col-size=\"md\">Empty array \u2192 crash<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Modifying array while iterating<\/td>\n<td data-col-size=\"lg\">for fruit in fruits { fruits.append(&#8220;\u2026&#8221;) }<\/td>\n<td data-col-size=\"lg\">Build new array or use indices \/ forEach<\/td>\n<td data-col-size=\"md\">Runtime error: collection mutated<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Forgetting enumerated() when needing index<\/td>\n<td data-col-size=\"lg\">for fruit in fruits { print(&#8220;1. \\(fruit)&#8221;) }<\/td>\n<td data-col-size=\"lg\">for (i, fruit) in fruits.enumerated() { print(&#8220;\\(i+1). \\(fruit)&#8221;) }<\/td>\n<td data-col-size=\"md\">Wrong numbering<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Using for i in 0&#8230;array.count<\/td>\n<td data-col-size=\"lg\">for i in 0&#8230;array.count { \u2026 }<\/td>\n<td data-col-size=\"lg\">for i in 0..&lt;array.count<\/td>\n<td data-col-size=\"md\">0&#8230;count tries to access index count \u2192 crash<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">5. Quick Reference \u2013 Which for style to choose<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"lg\">You want to do\u2026<\/th>\n<th data-col-size=\"lg\">Recommended style<\/th>\n<th data-col-size=\"md\">Why \/ When to prefer it<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"lg\">Just process each item (no position needed)<\/td>\n<td data-col-size=\"lg\">for item in array { \u2026 }<\/td>\n<td data-col-size=\"md\">Simplest &amp; most readable<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Need the position \/ want numbering<\/td>\n<td data-col-size=\"lg\">for (index, item) in array.enumerated() { \u2026 }<\/td>\n<td data-col-size=\"md\">Most common when showing numbered lists<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Only need indices (rare)<\/td>\n<td data-col-size=\"lg\">for index in array.indices { \u2026 }<\/td>\n<td data-col-size=\"md\">When modifying or using multiple parallel arrays<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Want 1-based numbering (user-facing)<\/td>\n<td data-col-size=\"lg\">for (index, item) in array.enumerated() { index + 1 }<\/td>\n<td data-col-size=\"md\">Natural for humans<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Repeat exact number of times<\/td>\n<td data-col-size=\"lg\">for i in 0..&lt;10 { \u2026 } or for i in 1&#8230;10 { \u2026 }<\/td>\n<td data-col-size=\"md\">Clear &amp; safe<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">6. Small Practice \u2013 Try these right now<\/h3>\n<ol dir=\"auto\">\n<li>Create array of 5 favorite movies \u2192 Print them numbered (1. Movie A, 2. Movie B\u2026)<\/li>\n<li>Create array of numbers 1\u202610 \u2192 Print each number and whether it is even or odd \u2192 Use both simple for and enumerated() style<\/li>\n<li>Create array of 6 task names \u2192 Print &#8220;Task 1: \u2026&#8221; up to &#8220;Task 6: \u2026&#8221; using index<\/li>\n<\/ol>\n<p dir=\"auto\">Paste your code here if you want feedback or want to see cleaner versions!<\/p>\n<p dir=\"auto\">What would you like to explore next?<\/p>\n<ul dir=\"auto\">\n<li><strong>forEach<\/strong>, <strong>map<\/strong>, <strong>filter<\/strong>, <strong>reduce<\/strong> (functional style)<\/li>\n<li>Looping with <strong>indices<\/strong> and <strong>safe bounds checking<\/strong><\/li>\n<li><strong>Sorting<\/strong> arrays (simple &amp; custom)<\/li>\n<li><strong>Array slicing<\/strong> &amp; ArraySlice lifetime<\/li>\n<li>Arrays in <strong>SwiftUI<\/strong> (List, ForEach, @State)<\/li>\n<li>Or move to another topic (dictionaries, sets, optionals\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. Why do we need a for loop? A for loop is the most natural way to say: \u201cPlease do this same thing once for every item in this list \/ collection \/ range.\u201d&#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-2702","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2702","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=2702"}],"version-history":[{"count":1,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2702\/revisions"}],"predecessor-version":[{"id":2703,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2702\/revisions\/2703"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2702"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2702"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2702"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}