{"id":2659,"date":"2026-02-05T08:45:17","date_gmt":"2026-02-05T08:45:17","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2659"},"modified":"2026-02-05T08:45:28","modified_gmt":"2026-02-05T08:45:28","slug":"chapter-37-swift-arrays-loop","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/chapter-37-swift-arrays-loop\/","title":{"rendered":"Chapter 37: Swift Arrays: Loop"},"content":{"rendered":"<h3 dir=\"auto\">1. Why do we need different ways to loop?<\/h3>\n<p dir=\"auto\">When you have an array, you usually want to:<\/p>\n<ul dir=\"auto\">\n<li>Do something <strong>with each item<\/strong><\/li>\n<li>Know the <strong>position<\/strong> (index) of each item<\/li>\n<li>Transform items into a new array<\/li>\n<li>Find something (first match, all matches\u2026)<\/li>\n<li>Sum, count, filter, or reduce values<\/li>\n<\/ul>\n<p dir=\"auto\">Swift gives you several very elegant ways to do this \u2014 and choosing the right one makes your code <strong>clearer, safer, and more efficient<\/strong>.<\/p>\n<h3 dir=\"auto\">2. The 5 most important ways to loop over arrays<\/h3>\n<h4 dir=\"auto\">Way 1 \u2013 Simple for-in loop (most common &amp; most readable)<\/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\"]\r\n\r\nfor fruit in fruits {\r\n    print(\"I like \\(fruit)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>When to use this:<\/strong><\/p>\n<ul dir=\"auto\">\n<li>You only need the <strong>value<\/strong> (not the index)<\/li>\n<li>You are doing something simple like printing, logging, calling a function, updating UI\u2026<\/li>\n<\/ul>\n<p dir=\"auto\"><strong>Real-life example \u2013 show list of tasks<\/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>let tasks = [\"Buy groceries\", \"Finish report\", \"Call mom\", \"Gym\"]\r\n\r\nprint(\"Today's tasks:\")\r\nfor task in tasks {\r\n    print(\"\u2022 \\(task)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Way 2 \u2013 for-in with index using enumerated()<\/h4>\n<p dir=\"auto\">This is <strong>the most common way when you need both the item and its position<\/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>let fruits = [\"Mango\", \"Banana\", \"Apple\", \"Orange\"]\r\n\r\nfor (index, fruit) in fruits.enumerated() {\r\n    print(\"\\(index + 1). \\(fruit)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Output:<\/strong><\/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. Mango\r\n2. Banana\r\n3. Apple\r\n4. Orange<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Real-life example \u2013 numbered list in console or debug log<\/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>let logs = [\r\n    \"User logged in\",\r\n    \"API call failed\",\r\n    \"Retry successful\",\r\n    \"Session ended\"\r\n]\r\n\r\nprint(\"Recent activity:\")\r\nfor (i, log) in logs.enumerated() {\r\n    print(\"  [\\(i + 1)] \\(log)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Way 3 \u2013 Loop over indices only (indices property)<\/h4>\n<p dir=\"auto\">Use this when you mainly need the <strong>positions<\/strong> and will access the array manually.<\/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 scores = [85, 92, 78, 95, 88]\r\n\r\nfor index in scores.indices {\r\n    let score = scores[index]\r\n    let grade = score &gt;= 90 ? \"A\" : score &gt;= 80 ? \"B\" : \"C\"\r\n    print(\"Student \\(index + 1): \\(grade)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>When to use this style:<\/strong><\/p>\n<ul dir=\"auto\">\n<li>You need to <strong>modify<\/strong> the array while looping (carefully!)<\/li>\n<li>You are working with multiple arrays at the same index<\/li>\n<li>You want maximum control over iteration<\/li>\n<\/ul>\n<h4 dir=\"auto\">Way 4 \u2013 forEach method (functional 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\"]\r\n\r\nfruits.forEach { fruit in\r\n    print(\"\u2192 I like \\(fruit)\")\r\n}\r\n\r\n\/\/ or shorter with implicit $0\r\nfruits.forEach {\r\n    print(\"\u2192 I like \\($0)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Key differences from for-in:<\/strong><\/p>\n<ul dir=\"auto\">\n<li>Cannot use break or continue<\/li>\n<li>Cannot return early from the function<\/li>\n<li>Looks more \u201cfunctional\u201d (good when chaining with map, filter\u2026)<\/li>\n<\/ul>\n<p dir=\"auto\"><strong>Realistic use case \u2013 small logging or side effects<\/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>let recentSearches = [\"Swift arrays\", \"String interpolation\", \"forEach vs for-in\"]\r\n\r\nrecentSearches.forEach { query in\r\n    print(\"User searched: \\(query)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Way 5 \u2013 Modern for try or for await (when dealing with throwing or async items)<\/h4>\n<p dir=\"auto\">These are advanced but very common in real apps today.<\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>\/\/ Example with throwing functions\r\nlet urls = [\r\n    URL(string: \"https:\/\/example.com\/1\")!,\r\n    URL(string: \"https:\/\/example.com\/2\")!\r\n]\r\n\r\nfor try await data in urls.asyncMap({ try await URLSession.shared.data(from: $0).0 }) {\r\n    print(\"Downloaded data of size: \\(data.count) bytes\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">(We\u2019ll cover async loops later \u2014 just showing it exists.)<\/p>\n<h3 dir=\"auto\">6. Very Common Real-Life Examples<\/h3>\n<h4 dir=\"auto\">Example 1 \u2013 Display numbered list in console or debug<\/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 recentMessages = [\r\n    \"Hey, how are you?\",\r\n    \"Meeting at 3 PM\",\r\n    \"Sent you the file\",\r\n    \"Thanks!\"\r\n]\r\n\r\nprint(\"Recent messages:\")\r\nfor (index, message) in recentMessages.enumerated() {\r\n    print(\"  \\(index + 1). \\(message)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 2 \u2013 Process items with position<\/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 items = [\"Phone\", \"Charger\", \"Case\", \"Screen guard\"]\r\n\r\nvar totalPrice: Double = 0\r\nvar receipt = \"Receipt:\\n\"\r\n\r\nfor (index, item) in items.enumerated() {\r\n    let price: Double\r\n    switch item {\r\n    case \"Phone\": price = 74999\r\n    case \"Charger\": price = 1999\r\n    case \"Case\": price = 999\r\n    case \"Screen guard\": price = 499\r\n    default: price = 0\r\n    }\r\n    \r\n    totalPrice += price\r\n    receipt += \"  \\(index + 1). \\(item) - \u20b9\\(price)\\n\"\r\n}\r\n\r\nreceipt += \"-------------------\\n\"\r\nreceipt += \"Total: \u20b9\\(totalPrice)\"\r\n\r\nprint(receipt)<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">Example 3 \u2013 Filter &amp; transform with forEach (functional 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 temperatures = [28.5, 32.1, 35.8, 29.4, 31.2]\r\n\r\ntemperatures.forEach { temp in\r\n    let status = temp &gt; 32 ? \"Hot \u2600\ufe0f\" : temp &lt; 30 ? \"Pleasant \ud83c\udf24\ufe0f\" : \"Warm \ud83d\ude05\"\r\n    print(\"\\(temp)\u00b0C \u2192 \\(status)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">7. Quick Summary \u2013 Which Loop Style to Choose<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"lg\">Situation<\/th>\n<th data-col-size=\"lg\">Recommended style<\/th>\n<th data-col-size=\"lg\">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 index needed)<\/td>\n<td data-col-size=\"lg\">for item in array { \u2026 }<\/td>\n<td data-col-size=\"lg\">Simplest, most readable<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Need the position (index)<\/td>\n<td data-col-size=\"lg\">for (index, item) in array.enumerated()<\/td>\n<td data-col-size=\"lg\">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=\"lg\">When modifying or using multiple arrays<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Functional style, chaining, side effects<\/td>\n<td data-col-size=\"lg\">array.forEach { \u2026 }<\/td>\n<td data-col-size=\"lg\">Looks modern, good for small operations<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Async \/ throwing items<\/td>\n<td data-col-size=\"lg\">for try await \u2026, for await \u2026<\/td>\n<td data-col-size=\"lg\">Modern concurrency code<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">8. Small Practice \u2013 Try these now<\/h3>\n<ol dir=\"auto\">\n<li>Create array of 5 favorite foods \u2192 Print them numbered using enumerated() \u2192 Print only items that contain &#8220;a&#8221; in the name<\/li>\n<li>Create array of numbers 1\u202610 \u2192 Print each number and whether it is even or odd \u2192 Use both for-in and forEach styles<\/li>\n<li>Create array of 4 task names \u2192 Print &#8220;Task 1: \u2026&#8221; up to &#8220;Task 4: \u2026&#8221; using index<\/li>\n<\/ol>\n<p dir=\"auto\">Paste your code if you want feedback or improvements!<\/p>\n<p dir=\"auto\">What would you like to explore next about arrays?<\/p>\n<ul dir=\"auto\">\n<li>Looping with <strong>filter<\/strong>, <strong>map<\/strong>, <strong>compactMap<\/strong>, <strong>reduce<\/strong><\/li>\n<li><strong>Sorting<\/strong> arrays (simple &amp; custom sorting)<\/li>\n<li><strong>Array slicing<\/strong> (prefix, suffix, dropFirst\u2026)<\/li>\n<li><strong>Safe index access<\/strong> &amp; bounds checking<\/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 keep going in the same clear, detailed, teacher-like style \ud83d\ude0a<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. Why do we need different ways to loop? When you have an array, you usually want to: Do something with each item Know the position (index) of each item Transform items into a&#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-2659","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2659","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=2659"}],"version-history":[{"count":1,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2659\/revisions"}],"predecessor-version":[{"id":2660,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2659\/revisions\/2660"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2659"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2659"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2659"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}