swift-style
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSwift Style Guide
Swift 代码风格指南
Code style conventions for clean, readable Swift code.
用于编写清晰、易读Swift代码的风格约定。
Core Principles
核心原则
Clarity > Brevity > Consistency
Code should compile without warnings.
清晰 > 简洁 > 一致
代码编译时应无警告。
Naming
命名规则
- — Types, protocols
UpperCamelCase - — Everything else
lowerCamelCase - Clarity at call site
- No abbreviations except universal (URL, ID)
swift
// Preferred
let maximumWidgetCount = 100
func fetchUser(byID id: String) -> User- — 类型、协议
UpperCamelCase - — 其他所有元素
lowerCamelCase - 调用处清晰明了
- 除通用缩写(URL、ID)外,禁止使用其他缩写
swift
// Preferred
let maximumWidgetCount = 100
func fetchUser(byID id: String) -> UserGolden Path
幸福路径原则
Left-hand margin is the happy path. Don't nest statements.
ifswift
// Preferred
func process(value: Int?) throws -> Result {
guard let value = value else {
throw ProcessError.nilValue
}
guard value > 0 else {
throw ProcessError.invalidValue
}
return compute(value)
}左侧边距对应正常流程(幸福路径)。不要嵌套语句。
ifswift
// Preferred
func process(value: Int?) throws -> Result {
guard let value = value else {
throw ProcessError.nilValue
}
guard value > 0 else {
throw ProcessError.invalidValue
}
return compute(value)
}Code Organization
代码组织结构
Use extensions and MARK comments:
swift
class MyViewController: UIViewController {
// Core implementation
}
// MARK: - UITableViewDataSource
extension MyViewController: UITableViewDataSource { }使用扩展和MARK注释:
swift
class MyViewController: UIViewController {
// Core implementation
}
// MARK: - UITableViewDataSource
extension MyViewController: UITableViewDataSource { }Spacing
空格规范
- Braces open on same line, close on new line
- One blank line between methods
- Colon: no space before, one space after
- 左大括号与代码同行,右大括号另起一行
- 方法之间空一行
- 冒号:前面无空格,后面有一个空格
Self
Self使用规则
Avoid unless required by compiler.
selfswift
// Preferred
func configure() {
backgroundColor = .systemBackground
}除非编译器要求,否则避免使用。
selfswift
// Preferred
func configure() {
backgroundColor = .systemBackground
}Computed Properties
计算属性
Omit for read-only:
getswift
var diameter: Double {
radius * 2
}只读计算属性省略关键字:
getswift
var diameter: Double {
radius * 2
}Closures
闭包使用
Trailing closure only for single closure parameter.
仅当只有一个闭包参数时使用尾随闭包。
Type Inference
类型推断
Let compiler infer when clear. For empty collections, use type annotation:
swift
var names: [String] = []在类型明确时让编译器自动推断。对于空集合,需添加类型注解:
swift
var names: [String] = []Syntactic Sugar
语法糖
swift
// Preferred
var items: [String]
var cache: [String: Int]
var name: String?swift
// Preferred
var items: [String]
var cache: [String: Int]
var name: String?Access Control
访问控制
- over
privatefileprivate - Don't add (it's the default)
internal - Access control as leading specifier
- 优先使用而非
privatefileprivate - 无需添加(它是默认权限)
internal - 访问控制修饰符放在最前面
Memory Management
内存管理
swift
resource.request().onComplete { [weak self] response in
guard let self else { return }
self.updateModel(response)
}swift
resource.request().onComplete { [weak self] response in
guard let self else { return }
self.updateModel(response)
}Comments
注释规范
- Explain why, not what
- Use or
//, avoid////* */ - Keep up-to-date or delete
- 解释原因,而非内容
- 使用或
//,避免使用////* */ - 保持注释更新或直接删除
Constants
常量定义
Use case-less enum for namespacing:
swift
enum Math {
static let pi = 3.14159
}使用无大小写的枚举来实现命名空间:
swift
enum Math {
static let pi = 3.14159
}Common Mistakes
常见错误
-
Abbreviations beyond URL, ID, UUID — Abbreviations like,
cfg,mgr,ctxhurt readability. Spell them out:desc,configuration,manager,context. The three exceptions are URL, ID, UUID.description -
Nested guard/if statements — Deep nesting makes code hard to follow. Use early returns and guards to keep the happy path left-aligned.
-
Inconsistent self usage — Either always omit(preferred) or always use it. Mixing makes code scanning harder and confuses capture semantics.
self -
Overly generic type names —,
Manager,Handler,Helperare too vague. Names should explain responsibility:Coordinator,PaymentProcessor,EventDispatcher,ImageCache.NavigationCoordinator -
Implied access control — Don't skip access control. Explicit,
privatehelps future maintainers understand module boundaries.publicis default, so omit it.internal
-
使用URL、ID、UUID之外的缩写 — 像、
cfg、mgr、ctx这类缩写会降低可读性,请完整拼写为desc、configuration、manager、context。仅URL、ID、UUID这三个缩写是允许的。description -
嵌套guard/if语句 — 深层嵌套会让代码难以理解。使用提前返回和guard语句,让正常流程保持左对齐。
-
Self使用不一致 — 要么始终省略(推荐),要么始终使用它。混合使用会增加代码阅读难度,还会混淆捕获语义。
self -
过于通用的类型名称 —、
Manager、Handler、Helper这类名称过于模糊。名称应明确说明职责:比如Coordinator、PaymentProcessor、EventDispatcher、ImageCache。NavigationCoordinator -
隐含访问控制 — 不要省略访问控制修饰符。显式的、
private有助于后续维护者理解模块边界。public是默认权限,因此可以省略。internal