CHAPTER 08
Beginner
Swift Collections: Arrays, Dictionaries, and Sets
Updated: May 16, 2026
6 min read
# CHAPTER 8
Swift Collections: Arrays, Dictionaries, and Sets
1. Introduction
A variable holds a single piece of data. An object holds a single model. But what if you are building an Instagram clone? You don't have one photo; you have an infinite feed of photos. You need a data structure capable of holding massive lists of items. In Swift, these structures are called Collections. In this chapter, we will master the three core Swift Collections: Arrays (for ordered lists), Dictionaries (for fast key-value lookups), and Sets (for guaranteeing uniqueness).2. Learning Objectives
By the end of this chapter, you will be able to:- Create, modify, and iterate over Swift Arrays.
- Understand zero-based indexing to extract array items.
- Store and retrieve data using Key-Value pairs in Dictionaries.
- Utilize Sets to perform ultra-fast math and ensure unique data.
-
Combine Collections with
for-inloops to render data.
3. Arrays (Ordered Lists)
An Array is a list of items stored in a specific order. Because Swift is Type-Safe, an array can only hold ONE type of data (e.g., an array of Strings, or an array of Integers. You cannot mix them).
swift
Zero-Based Indexing: To grab an item out of an array, you ask for its position (Index). In computer science, we always start counting at Zero!
swift
4. Dictionaries (Key-Value Pairs)
If you want to look up a user's phone number, an Array is terrible (you'd have to search millions of items one by one). A Dictionary is perfect. It stores data in Key-Value pairs. You provide the Key, and it instantly hands you the Value!
swift
5. Sets (Unordered & Unique)
A Set looks exactly like an Array, but it has two massive differences:- 1. It has NO order (No indexing).
- 2. Every item MUST be unique. If you try to add "Apple" twice, it simply ignores the second one!
Sets are incredibly fast for searching.
swift
6. Iterating through Collections
The true power of collections is automating them using thefor-in loop we learned in Chapter 5.
Looping an Array:
swift
Looping a Dictionary: (It provides both the Key and Value!)
swift
7. Higher-Order Functions (Advanced Magic)
Swift Collections have built-in superpowers like.filter and .map. These allow you to manipulate entire arrays in a single line of code without using heavy for loops!
swift
8. Common Mistakes
-
Index Out of Range: The absolute most common crash in iOS development is
Fatal Error: Index out of range. If an array has 3 items, its indexes are 0, 1, and 2. If your code asks forshoppingList[3], the app will instantly crash because that slot does not exist. Always check.countfirst!
-
Dictionary Nulls: When you ask a Dictionary for a value (
phoneBook["Dave"]), what if Dave isn't in the book? Swift doesn't crash; it returnsnil(nothing). We will learn how to handlenilin the next chapter!
9. Best Practices
- Use Arrays for UI Lists: If you are building a feed (like Twitter or Instagram), always use an Array because the *order* of the posts matters.
- Use Dictionaries for JSON: When you download data from the internet (JSON), it almost always comes formatted as Dictionaries (Key-Value pairs).
10. Exercises
-
1.
Create an Array of Strings named
colorscontaining "Red", "Green", and "Blue". Append "Yellow" to it.
-
2.
Create a Dictionary named
inventorywhere the Keys are Strings (item names) and the Values are Integers (quantity). Add an item.
11. Coding Challenges
Challenge: Create an array of Integers[5, 10, 15, 20]. Write a for-in loop that iterates over the array, multiplies each number by 2, and prints the result to the console.
12. MCQ Quiz with Answers
Question 1
In Swift, what is the defining characteristic of a Set compared to an Array?
Question 2
If you execute var list = ["A", "B", "C"] and then call print(list[1]), what will be printed to the console?
13. Interview Questions
- Q: Contrast Arrays, Dictionaries, and Sets. Provide a specific, real-world iOS app scenario for when you would choose each specific collection type over the others.
-
Q: Explain the concept of "Zero-Based Indexing". Why does calling
array[array.count]result in a fatal "Index out of bounds" crash?
-
Q: Briefly describe how higher-order functions like
.filterand.mapimprove architectural readability over standardforloops.
14. FAQs
Q: Can I put Objects (like my customPlayer struct) inside an Array?
A: Absolutely! This is how all modern iOS apps work. You create a struct Post, and then your app holds a var feed: [Post] = []. You can fill it with 10,000 custom post objects!
15. Summary
In Chapter 8, we expanded our memory capacity from single variables to massive Collections. We established ordered data structures using Arrays, mastering zero-based indexing to extract data. We built lightning-fast lookup tables using Dictionaries, associating unique Keys with data Values. We ensured data uniqueness utilizing Sets, and leveraged our knowledge of Control Flow to iterate across these vast datasets seamlessly usingfor-in loops.
16. Next Chapter Recommendation
We hinted earlier that asking a Dictionary for a missing key returnsnil. In older languages, nil destroys applications. Swift was built to survive it. Proceed to Chapter 9: Optionals and Error Handling.