Swift Overview
Swift 的核心不是一堆语法,而是一套关于 Type、Value、Behavior、Memory、Safety 和 Concurrency 的语言模型。
这组文档的目标不是重写 Swift 教材,而是建立一张“默认归位地图”:以后遇到一个 Swift 概念,先知道它属于哪一层,再去看语法和 API。
1. Core Mental Map
Swift
│
├── Type System
│ ├── struct
│ ├── class
│ ├── enum
│ ├── actor
│ └── protocol
│
├── Value & Reference Semantics
│ ├── Value Semantics
│ └── Reference Semantics
│
├── Instance & Lifetime
│
├── Member System
│ ├── Property
│ ├── Method
│ ├── Initializer
│ ├── Subscript
│ └── Nested Type
│
├── Function & Closure
│
├── Access & Dispatch
│
├── Memory
│ ├── Storage
│ ├── Reference Counting
│ └── Ownership
│
├── Protocol
│
├── Generics
│
├── Collections
│
├── Error & Optional
│
└── Concurrency
2. A Useful Learning Direction
Type
↓
Instance / Type itself
↓
Member
↓
Access
↓
Execution
↓
Memory / Lifetime
3. How to Place New Concepts
| 遇到的概念 | 先归到哪里 | 还会关联哪里 |
|---|---|---|
static property | Member System | Type System |
person.sayHello() | Member System | Access & Dispatch |
map | Collection Model | Function & Closure |
closure capture | Function & Closure | Instance & Lifetime / Memory |
weak self | Memory Model | Function & Closure / Lifetime |
Optional | Error & Optional | Type System |
protocol extension | Protocol Model | Dispatch / Generics |
async throws | Concurrency Model | Error & Optional |
判断顺序:
What type is this?
↓
Is it a type itself or an instance?
↓
What member is being accessed?
↓
Is it only access, or is it being called?
↓
What lifetime / memory / safety rule is involved?
4. Important Principle
Do not use syntax symbols as the primary conceptual anchor.
For example:
. is syntax.
The deeper concept is:
Type → Member → Access
Similarly:
() is syntax for calling something callable.
The deeper concept is:
Function / Method → Call → Execution
5. Type Is a Major Anchor
Many Swift concepts can be understood by asking:
What Type is this?
Then:
Is this a Type itself or an Instance?
Then:
What Members does it have?
Then:
How is the Member accessed?
6. Safety as a Design Theme
Swift emphasizes catching many mistakes through the type system and compiler.
Examples:
- Type Safety
- Optional
- Access Control
- Memory Safety
- Concurrency Safety
7. Mental Model vs Syntax
Mental Model:
What is this thing and how does it relate to other things?
Syntax:
How do I write it?
Learn the model first when possible, then use syntax as its expression.