Collections, Optionals, and Error Handling
Collections
Array is ordered and index-based; Dictionary maps unique keys to values; Set stores unique hashable elements with no order. All three are value types with copy-on-write. Dictionary subscripting returns an optional because a key may be absent, so dict[key] = nil removes an entry. Mutating a collection while iterating it can invalidate indices; collect changes first.
Optionals
An optional represents either a value or nil. Unwrap with if let, guard let, ??, optional chaining, or pattern matching. Force unwrapping and implicitly unwrapped optionals crash if the value is absent; use them only when an invariant is guaranteed. map transforms the wrapped value, while flatMap avoids nested optionals.
Functional helpers
map transforms every element, compactMap drops nil results and unwraps, filter keeps matching elements, and reduce folds to one value. Chaining them is idiomatic, but avoid side effects inside these closures.
Errors
A type conforming to Error can be thrown with throw. A throwing function is marked throws; callers use do/catch, try? (returns an optional, discarding the error), or try! (traps on error). Catches must be exhaustive unless a final catch handles everything. defer runs on every exit path, including throws. Initializers can be failable (init?) or throwing.
Traps
- Treating a dictionary lookup as non-optional.
- Using
try?and losing the underlying error. - Forgetting that
compactMapflattens one optional level. - Assuming
Setpreserves insertion order.
Rule of thumb
Push optionals to the boundary: unwrap early with guard let, keep interior code non-optional, and translate errors into user-facing messages at the presentation layer.