1---2name: swift3description: Write safe Swift code avoiding memory leaks, optional traps, and concurrency bugs.4---5
6## Quick Reference
7
8| Topic | File |
9|-------|------|
10| Optionals, nil safety, force unwrap | `optionals.md` |
11| Retain cycles, weak refs, closures | `memory.md` |
12| async/await, actors, Sendable, value types | `concurrency.md` |
13| JSON encoding/decoding traps | `codable.md` |
14| Protocols, collections, strings, errors, build | `types.md` |
15| SwiftUI state (@State, @Binding, Combine) | `swiftui.md` |
16| Property wrappers, actors, result builders, macros | `advanced.md` |
17| XCTest pitfalls, SPM gotchas | `testing.md` |
18
19## Critical Rules
20
21### Memory & Safety
22- Force unwrap `!` crashes on nil — use `guard let` or `if let` instead
23- Closures capturing `self` strongly create retain cycles — use `[weak self]` in escaping closures
24- Delegates must be `weak` — strong delegate = object never deallocates
25- `try!` crashes on any error — never use in production paths
26- `removeFirst()` crashes on empty — use `popFirst()` for safety
27
28### Concurrency
29- `async let` starts immediately — not when you `await`
30- Actor reentrancy at every `await` — state may change between suspension points
31- `@MainActor` doesn't guarantee immediate main thread — it's queued
32- `Sendable` conformance violations crash at runtime — compiler warnings are errors
33
34### Types & Collections
35- Protocol extensions don't override — static dispatch ignores subclass implementation
36- Mutating struct in collection requires reassignment — `array[0].mutate()` doesn't work
37- `String.Index` from one string invalid on another — even if contents match
38
39### SwiftUI
40- `@StateObject` owns, `@ObservedObject` borrows — recreating view loses ObservedObject state
41- `@EnvironmentObject` crashes if not injected — no compile-time check
42- View identity change resets all `@State` — changing ID loses state
43
44### Build
45- `print()` builds strings even in release — remove or use os_log
46- Generic code bloat — specialized for each type, increases binary size