{"id":2712,"date":"2026-02-05T11:09:16","date_gmt":"2026-02-05T11:09:16","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2712"},"modified":"2026-02-05T11:09:16","modified_gmt":"2026-02-05T11:09:16","slug":"chapter-63-swift-collections","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/chapter-63-swift-collections\/","title":{"rendered":"Chapter 63: Swift Collections"},"content":{"rendered":"<h3 dir=\"auto\">The Big Picture: What are Collections and Why Three Main Types?<\/h3>\n<p dir=\"auto\">A <strong>collection<\/strong> in Swift is any type that holds <strong>zero or more values<\/strong>.<\/p>\n<p dir=\"auto\">Swift gives you <strong>three main choices<\/strong> for everyday work \u2014 each solves a different problem:<\/p>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"md\">Collection Type<\/th>\n<th data-col-size=\"md\">Ordered?<\/th>\n<th data-col-size=\"lg\">Allows duplicates?<\/th>\n<th data-col-size=\"md\">Fast lookup by value?<\/th>\n<th data-col-size=\"md\">Fast lookup by key?<\/th>\n<th data-col-size=\"xl\">Most common real-life feeling<\/th>\n<th data-col-size=\"xl\">Typical use case examples<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"md\"><strong>Array<\/strong><\/td>\n<td data-col-size=\"md\">Yes<\/td>\n<td data-col-size=\"lg\">Yes<\/td>\n<td data-col-size=\"md\">No (slow)<\/td>\n<td data-col-size=\"md\">No<\/td>\n<td data-col-size=\"xl\">\u201cI have a list of things in a specific order\u201d<\/td>\n<td data-col-size=\"xl\">shopping cart, to-do list, recent searches, messages<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\"><strong>Set<\/strong><\/td>\n<td data-col-size=\"md\">No<\/td>\n<td data-col-size=\"lg\"><strong>No<\/strong><\/td>\n<td data-col-size=\"md\">Yes (very fast)<\/td>\n<td data-col-size=\"md\">No<\/td>\n<td data-col-size=\"xl\">\u201cI have a group of unique items \u2014 order doesn\u2019t matter\u201d<\/td>\n<td data-col-size=\"xl\">tags, permissions, unique IDs, friends list (no duplicates)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\"><strong>Dictionary<\/strong><\/td>\n<td data-col-size=\"md\">No (insertion order since Swift 4.2)<\/td>\n<td data-col-size=\"lg\">Yes (different keys)<\/td>\n<td data-col-size=\"md\">No<\/td>\n<td data-col-size=\"md\">Yes (very fast)<\/td>\n<td data-col-size=\"xl\">\u201cI have items and I want to find them by a key\/label\u201d<\/td>\n<td data-col-size=\"xl\">user profile, JSON data, settings, lookup tables<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Golden rule you should burn into your mind:<\/strong><\/p>\n<blockquote dir=\"auto\">\n<ul dir=\"auto\">\n<li>Need <strong>order<\/strong> or <strong>duplicates<\/strong> \u2192 almost always <strong>Array<\/strong><\/li>\n<li>Need <strong>uniqueness<\/strong> and <strong>fast \u201cdoes it contain X?\u201d<\/strong> \u2192 <strong>Set<\/strong><\/li>\n<li>Need <strong>fast lookup by key<\/strong> (\u201cgive me value for this name\/ID\u201d) \u2192 <strong>Dictionary<\/strong><\/li>\n<\/ul>\n<\/blockquote>\n<h3 dir=\"auto\">Chapter 2 \u2013 Arrays (the most common collection \u2013 you will use this 70\u201380% of the time)<\/h3>\n<h4 dir=\"auto\">2.1 Creating &amp; basic operations<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>\/\/ Most common ways\r\nlet colors: [String] = [\"Red\", \"Green\", \"Blue\"]          \/\/ type annotation optional\r\nvar shoppingCart = [String]()                           \/\/ empty mutable array\r\n\r\n\/\/ Add items\r\nshoppingCart.append(\"Milk\")\r\nshoppingCart.append(contentsOf: [\"Bread\", \"Eggs\"])\r\n\r\n\/\/ Insert at specific position\r\nshoppingCart.insert(\"Butter\", at: 1)\r\n\r\n\/\/ Replace\r\nshoppingCart[0] = \"Almond Milk\"\r\n\r\n\/\/ Remove\r\nshoppingCart.remove(at: 2)           \/\/ removes \"Eggs\"\r\nlet lastItem = shoppingCart.removeLast()\r\n\r\n\/\/ Count &amp; empty check\r\nprint(shoppingCart.count)            \/\/ 2\r\nprint(shoppingCart.isEmpty)          \/\/ false\r\n\r\n\/\/ Safe first\/last\r\nlet first = shoppingCart.first ?? \"No items\"<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h4 dir=\"auto\">2.2 Real-life example \u2013 shopping cart \/ order summary<\/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\nvar cart: [CartItem] = []\r\n\r\ncart.append(CartItem(name: \"Wireless Earbuds\", price: 3499, quantity: 1))\r\ncart.append(CartItem(name: \"Phone Case\",       price: 799,  quantity: 2))\r\ncart.append(CartItem(name: \"Screen Protector\", price: 499,  quantity: 1))\r\n\r\nprint(\"Your Cart (\\(cart.count) items)\")\r\nprint(\"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\")\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(\"\u2500\u2500\")\r\n}\r\n\r\nprint(\"Grand Total: \u20b9\\(String(format: \"%.2f\", total))\")<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">Chapter 3 \u2013 Sets (when uniqueness matters)<\/h3>\n<h4 dir=\"auto\">3.1 Creating &amp; basic operations<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>var tags = Set&lt;String&gt;()\r\n\r\ntags.insert(\"Swift\")\r\ntags.insert(\"iOS\")\r\ntags.insert(\"Beginner\")\r\ntags.insert(\"Swift\")        \/\/ duplicate \u2013 ignored\r\n\r\nprint(tags)                 \/\/ Set([\"Swift\", \"iOS\", \"Beginner\"])\r\n\r\nprint(tags.contains(\"Swift\"))     \/\/ true\r\nprint(tags.contains(\"Python\"))    \/\/ false\r\n\r\n\/\/ Add multiple\r\ntags.formUnion([\"Apple\", \"Xcode\"])\r\n\r\n\/\/ Remove\r\ntags.remove(\"Beginner\")\r\n\r\n\/\/ Count\r\nprint(tags.count)           \/\/ 5<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Real-life example \u2013 unique permissions \/ roles<\/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>var userPermissions = Set&lt;String&gt;()\r\n\r\nuserPermissions.insert(\"read\")\r\nuserPermissions.insert(\"write\")\r\nuserPermissions.insert(\"delete\")\r\nuserPermissions.insert(\"read\")     \/\/ ignored\r\n\r\nif userPermissions.contains(\"delete\") {\r\n    print(\"User can delete content\")\r\n}\r\n\r\nif userPermissions.isSuperset(of: [\"read\", \"write\"]) {\r\n    print(\"User has read &amp; write access\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">Chapter 4 \u2013 Dictionaries (lookup by key)<\/h3>\n<h4 dir=\"auto\">4.1 Creating &amp; basic operations<\/h4>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>var profile: [String: Any] = [\r\n    \"name\": \"Rahul Verma\",\r\n    \"age\": 27,\r\n    \"city\": \"Bengaluru\",\r\n    \"isPremium\": true,\r\n    \"points\": 14520\r\n]\r\n\r\n\/\/ Access\r\nif let name = profile[\"name\"] as? String {\r\n    print(\"Name: \\(name)\")\r\n}\r\n\r\n\/\/ Update\r\nprofile[\"points\"] = 15000\r\n\r\n\/\/ Add new\r\nprofile[\"favoriteColor\"] = \"Blue\"\r\n\r\n\/\/ Remove\r\nprofile[\"age\"] = nil\r\n\r\n\/\/ Loop\r\nfor (key, value) in profile {\r\n    print(\"\\(key): \\(value)\")\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Real-life example \u2013 user profile \/ settings<\/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>var userSettings: [String: Any] = [\r\n    \"darkMode\": true,\r\n    \"notificationsEnabled\": true,\r\n    \"fontSize\": 16,\r\n    \"language\": \"en\",\r\n    \"locationSharing\": false\r\n]\r\n\r\n\/\/ Apply settings\r\nif let darkMode = userSettings[\"darkMode\"] as? Bool, darkMode {\r\n    applyDarkTheme()\r\n}\r\n\r\nif let fontSize = userSettings[\"fontSize\"] as? CGFloat {\r\n    setFontSize(fontSize)\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Modern style (strongly typed dictionary)<\/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>enum SettingKey: String {\r\n    case darkMode\r\n    case notificationsEnabled\r\n    case fontSize\r\n    case language\r\n}\r\n\r\nvar typedSettings: [SettingKey: Any] = [\r\n    .darkMode: true,\r\n    .fontSize: 16\r\n]<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">Chapter 5 \u2013 Quick Comparison Table (keep this in mind)<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"lg\">You want to&#8230;<\/th>\n<th data-col-size=\"sm\">Use this collection<\/th>\n<th data-col-size=\"lg\">Typical operations<\/th>\n<th data-col-size=\"xl\">Example real-life case<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"lg\">Keep order, allow duplicates<\/td>\n<td data-col-size=\"sm\">Array<\/td>\n<td data-col-size=\"lg\">append, insert(at:), remove(at:), enumerated()<\/td>\n<td data-col-size=\"xl\">shopping cart, task list, chat messages<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Ensure uniqueness, fast \u201ccontains?\u201d<\/td>\n<td data-col-size=\"sm\">Set<\/td>\n<td data-col-size=\"lg\">insert, contains, remove, union\/intersection<\/td>\n<td data-col-size=\"xl\">tags, permissions, unique IDs, friends (no dupes)<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"lg\">Fast lookup by key<\/td>\n<td data-col-size=\"sm\">Dictionary<\/td>\n<td data-col-size=\"lg\">[key] = value, updateValue(forKey:), removeValue<\/td>\n<td data-col-size=\"xl\">user profile, settings, JSON data, lookup tables<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">Chapter 6 \u2013 Small Practice \u2013 Try these<\/h3>\n<ol dir=\"auto\">\n<li>Create an <strong>array<\/strong> of 5 favorite foods \u2192 Print them numbered \u2192 Add one more at the beginning \u2192 Remove the last one<\/li>\n<li>Create a <strong>set<\/strong> of 6 tags (some duplicates) \u2192 Add 2 more \u2192 Check if &#8220;Swift&#8221; is present \u2192 Print all unique tags<\/li>\n<li>Create a <strong>dictionary<\/strong> for a user profile \u2192 name, age, city, isPremium \u2192 Print all key-value pairs \u2192 Change age and add favoriteColor<\/li>\n<\/ol>\n<p dir=\"auto\">Paste your code here if you want feedback or want to see more polished versions!<\/p>\n<p dir=\"auto\">What would you like to explore next?<\/p>\n<ul dir=\"auto\">\n<li><strong>Array<\/strong> slicing &amp; memory behavior with slices<\/li>\n<li><strong>Sorting<\/strong> arrays (simple &amp; custom comparators)<\/li>\n<li><strong>Filtering<\/strong>, <strong>mapping<\/strong>, <strong>reducing<\/strong> in depth<\/li>\n<li><strong>Dictionaries<\/strong> in more depth (typed keys, default values)<\/li>\n<li><strong>Sets<\/strong> operations (union, intersection, difference)<\/li>\n<li>Or move to another topic (optionals, switch, functions\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>The Big Picture: What are Collections and Why Three Main Types? A collection in Swift is any type that holds zero or more values. Swift gives you three main choices for everyday work \u2014&#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-2712","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2712","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=2712"}],"version-history":[{"count":1,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2712\/revisions"}],"predecessor-version":[{"id":2713,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2712\/revisions\/2713"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2712"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2712"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2712"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}