Arrays, dictionaries and sets

Swift · Essentials · 12 min

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 be Hashable.
  • 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)             // 3

Remember

  • 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.

Check yourself

  1. `var a = [1, 2]; var b = a; b.append(3)` — what is `a.count`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.swift.org/swift-book/documentation/the-swift-programming-language/collectiontypes/