swift-style

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Swift Style Guide

Swift 代码风格指南

Code style conventions for clean, readable Swift code.
用于编写清晰、易读Swift代码的风格约定。

Core Principles

核心原则

Clarity > Brevity > Consistency
Code should compile without warnings.
清晰 > 简洁 > 一致
代码编译时应无警告。

Naming

命名规则

  • UpperCamelCase
    — Types, protocols
  • lowerCamelCase
    — Everything else
  • 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) -> User

Golden Path

幸福路径原则

Left-hand margin is the happy path. Don't nest
if
statements.
swift
// 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)
}
左侧边距对应正常流程(幸福路径)。不要嵌套
if
语句。
swift
// 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
self
unless required by compiler.
swift
// Preferred
func configure() {
    backgroundColor = .systemBackground
}
除非编译器要求,否则避免使用
self
swift
// Preferred
func configure() {
    backgroundColor = .systemBackground
}

Computed Properties

计算属性

Omit
get
for read-only:
swift
var diameter: Double {
    radius * 2
}
只读计算属性省略
get
关键字:
swift
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

访问控制

  • private
    over
    fileprivate
  • Don't add
    internal
    (it's the default)
  • Access control as leading specifier
  • 优先使用
    private
    而非
    fileprivate
  • 无需添加
    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

常见错误

  1. Abbreviations beyond URL, ID, UUID — Abbreviations like
    cfg
    ,
    mgr
    ,
    ctx
    ,
    desc
    hurt readability. Spell them out:
    configuration
    ,
    manager
    ,
    context
    ,
    description
    . The three exceptions are URL, ID, UUID.
  2. Nested guard/if statements — Deep nesting makes code hard to follow. Use early returns and guards to keep the happy path left-aligned.
  3. Inconsistent self usage — Either always omit
    self
    (preferred) or always use it. Mixing makes code scanning harder and confuses capture semantics.
  4. Overly generic type names
    Manager
    ,
    Handler
    ,
    Helper
    ,
    Coordinator
    are too vague. Names should explain responsibility:
    PaymentProcessor
    ,
    EventDispatcher
    ,
    ImageCache
    ,
    NavigationCoordinator
    .
  5. Implied access control — Don't skip access control. Explicit
    private
    ,
    public
    helps future maintainers understand module boundaries.
    internal
    is default, so omit it.
  1. 使用URL、ID、UUID之外的缩写 — 像
    cfg
    mgr
    ctx
    desc
    这类缩写会降低可读性,请完整拼写为
    configuration
    manager
    context
    description
    。仅URL、ID、UUID这三个缩写是允许的。
  2. 嵌套guard/if语句 — 深层嵌套会让代码难以理解。使用提前返回和guard语句,让正常流程保持左对齐。
  3. Self使用不一致 — 要么始终省略
    self
    (推荐),要么始终使用它。混合使用会增加代码阅读难度,还会混淆捕获语义。
  4. 过于通用的类型名称
    Manager
    Handler
    Helper
    Coordinator
    这类名称过于模糊。名称应明确说明职责:比如
    PaymentProcessor
    EventDispatcher
    ImageCache
    NavigationCoordinator
  5. 隐含访问控制 — 不要省略访问控制修饰符。显式的
    private
    public
    有助于后续维护者理解模块边界。
    internal
    是默认权限,因此可以省略。