Quick Reference
| Topic | File |
|---|
| Optionals, nil safety, force unwrap | INLINECODE0 |
| Retain cycles, weak refs, closures |
memory.md |
| async/await, actors, Sendable, value types |
concurrency.md |
| JSON encoding/decoding traps |
codable.md |
| Protocols, collections, strings, errors, build |
types.md |
| SwiftUI state (@State, @Binding, Combine) |
swiftui.md |
| Property wrappers, actors, result builders, macros |
advanced.md |
| XCTest pitfalls, SPM gotchas |
testing.md |
Critical Rules
Memory & Safety
- - Force unwrap
! crashes on nil — use guard let or if let instead - Closures capturing
self strongly create retain cycles — use [weak self] in escaping closures - Delegates must be
weak — strong delegate = object never deallocates - INLINECODE14 crashes on any error — never use in production paths
- INLINECODE15 crashes on empty — use
popFirst() for safety
Concurrency
- -
async let starts immediately — not when you INLINECODE18 - Actor reentrancy at every
await — state may change between suspension points - INLINECODE20 doesn't guarantee immediate main thread — it's queued
- INLINECODE21 conformance violations crash at runtime — compiler warnings are errors
Types & Collections
- - Protocol extensions don't override — static dispatch ignores subclass implementation
- Mutating struct in collection requires reassignment —
array[0].mutate() doesn't work - INLINECODE23 from one string invalid on another — even if contents match
SwiftUI
- -
@StateObject owns, @ObservedObject borrows — recreating view loses ObservedObject state - INLINECODE26 crashes if not injected — no compile-time check
- View identity change resets all
@State — changing ID loses state
Build
- -
print() builds strings even in release — remove or use os_log - Generic code bloat — specialized for each type, increases binary size
快速参考
| 主题 | 文件 |
|---|
| 可选值、nil安全、强制解包 | optionals.md |
| 循环引用、弱引用、闭包 |
memory.md |
| async/await、Actor、Sendable、值类型 | concurrency.md |
| JSON编解码陷阱 | codable.md |
| 协议、集合、字符串、错误、构建 | types.md |
| SwiftUI状态(@State、@Binding、Combine) | swiftui.md |
| 属性包装器、Actor、结果构建器、宏 | advanced.md |
| XCTest陷阱、SPM注意事项 | testing.md |
关键规则
内存与安全
- - 强制解包 ! 在nil时会崩溃——应使用 guard let 或 if let 替代
- 闭包强捕获 self 会导致循环引用——逃逸闭包中应使用 [weak self]
- 代理必须声明为 weak——强引用代理会导致对象永远无法释放
- try! 在任何错误下都会崩溃——切勿在生产路径中使用
- removeFirst() 在空集合上会崩溃——安全起见应使用 popFirst()
并发
- - async let 会立即启动——而非在 await 时启动
- Actor在每次 await 处存在重入问题——状态可能在挂起点之间发生变化
- @MainActor 不保证立即在主线程执行——它会被加入队列
- 违反 Sendable 协议一致性会在运行时崩溃——编译器警告应视为错误
类型与集合
- - 协议扩展不会覆盖——静态分发忽略子类实现
- 修改集合中的结构体需要重新赋值——array[0].mutate() 无法生效
- 一个字符串的 String.Index 对另一个字符串无效——即使内容相同
SwiftUI
- - @StateObject 拥有所有权,@ObservedObject 借用所有权——重新创建视图会丢失ObservedObject状态
- @EnvironmentObject 若未注入则会崩溃——没有编译时检查
- 视图标识变化会重置所有 @State——改变ID会丢失状态
构建
- - print() 在发布版本中仍会构建字符串——应移除或使用 os_log
- 泛型代码膨胀——为每种类型特化,增加二进制体积