Collections hold almost all app data, and their value semantics behave differently from Java or JavaScript.
Swift's three core collections are generic value types:
Array<Element>, written[Int]— ordered, indexed from 0.Dictionary<Key, Value>, written[String: Int]— unordered key/value pairs; keys must beHashable.Set<Element>— unique, unordered, fast membership tests.
Declaring with let makes the collection fully immutable; with var you can append, insert, remove(at:) and assign subscripts. Because they are value types, var b = a gives b its own logical copy; changing b never affects a (storage is shared until a write, so copying is cheap).
Out-of-range array indexing traps. Use first, last, or check indices.contains(i) when unsure. Dictionary subscripts return an optional, since the key may be missing; dict[key, default: 0] += 1 is the idiom for counting.
Collections support functional methods that take closures: map, filter, reduce, compactMap (drops nils), sorted(by:), contains(where:), first(where:). Iterate dictionaries with for (key, value) in dict and arrays with indexes via for (i, x) in array.enumerated().
Sets offer union, intersection, subtracting and isSubset(of:).
Example
var scores = [72, 95, 88]
scores.append(60)
let passed = scores.filter { $0 >= 70 } // [72, 95, 88]
let total = scores.reduce(0, +) // 315
var copy = scores
copy[0] = 0
print(scores[0], copy[0]) // 72 0 (value semantics)
let words = ["a", "b", "a", "c", "a"]
var counts: [String: Int] = [:]
for w in words { counts[w, default: 0] += 1 }
print(counts["a"] ?? 0) // 3
print(counts["z"] as Any) // nil
let tags: Set = ["swift", "ios"]
print(tags.contains("ios")) // true
print(tags.union(["mac"]).count) // 3Remember
- Array, Dictionary and Set are value types
- Dictionary lookup returns an optional; use
[k, default: v]to count - Out-of-bounds array access traps
Watch out for
- Assuming a dictionary or set iterates in insertion order — it doesn't.