Activity 1
Choose the collection
Choose Array, Set, or Dictionary for a playlist order, selected category IDs, and a user lookup by ID. Explain why.
Hint: Ask whether order, uniqueness, or keyed retrieval is the primary need.
Swift Fundamentals
Store groups of values using collection types chosen for order, uniqueness, and lookup.
Before you begin
Learning stage
Swift provides Array for ordered values, Set for unique hashable values, and Dictionary for key-value associations. All elements in a collection share compatible types.
Collection choice communicates requirements. Choose based on whether order, duplicate values, membership checks, or keyed lookup matter to the feature.
Learning stage
The example uses each collection for a different requirement.
var lessonOrder = ["Types", "Functions", "Optionals"]
var completed: Set<String> = ["Types"]
var minutesByLesson = ["Types": 12, "Functions": 13]
lessonOrder.append("Collections")
completed.insert("Functions")
minutesByLesson["Optionals"] = 15
for lesson in lessonOrder {
let status = completed.contains(lesson) ? "Done" : "Next"
print("\(lesson): \(status)")
}Learning stage
These concepts appear throughout production iOS code. Focus on the requirement each technique communicates.
Learning stage
Notice these mistakes early so the compiler and type system can help instead of becoming obstacles.
Learning stage
Work through these activities in a small Xcode project. No embedded playground is required on this site.
Activity 1
Choose Array, Set, or Dictionary for a playlist order, selected category IDs, and a user lookup by ID. Explain why.
Hint: Ask whether order, uniqueness, or keyed retrieval is the primary need.
Activity 2
Create a function that returns the first lesson title or “No lessons” without indexing the array directly.
Hint: The first property returns an optional.
Learning stage
Answer each question before revealing the explanation.
QUESTION 1
Set
A set stores each Hashable element at most once.
QUESTION 2
An optional value, because the key might not exist.
Learning stage
Explain the idea in terms of its purpose, behavior, and tradeoffs rather than reciting syntax.
Short answer: Use Array for order, Set for unique membership, and Dictionary for lookup by key.
The decision should follow the operation and invariant the model needs. Arrays provide positional order, sets express uniqueness and efficient membership, and dictionaries associate keys with values. Performance matters, but semantic intent comes first.
Possible follow-ups
Learning stage
Collections are not interchangeable containers. Pick the type whose guarantees match the problem, and use safe APIs instead of assuming an index or key exists.