蓝色天空网mbsky.com · 知识 · 实践 · 创造Swift · 本地阅读预览
教程 / 移动开发 / Swift

Swift 编码规范

系统核对官方 Swift API Design Guidelines 六大核心准则、大小写与布尔前缀/去缩写命名约定、swift-format 排版与缩进规范、let/guard/if let 简写/值类型/协议扩展惯用法、十项反模式对照及常见问答。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

官方 API 设计指南与命名约定

统一的编码规范能大幅降低多人协作的阅读与审查摩擦。Swift 社区以官方《API Design Guidelines》为核心共识,其首要原则是**调用处清晰高于一切(Clarity at the point of use)**:类型和参数按角色命名而非堆砌重复类型名;参数标签与方法名共同读起来应像通顺的英文短语(注:Swift 3 起 SE-0046 规定第一个参数默认也带有外标签以与后续参数保持一致,当方法名已完整表达宾语时再显式用 `_` 省略);有副作用的原地修改方法用动词原形(如 `sort()`、`append(_:)`),返回新值的无副作用版本则加 `-ed`/`-ing` 后缀(如 `sorted()`、`trimmingCharacters(in:)`);同时用 `///` 文档注释写清行为契约、参数含义、返回值与可能抛出的错误。

在词法大小写上,类型、协议与泛型参数使用 `UpperCamelCase`(如 `OrderService`、`Element`),变量、属性、函数与枚举成员使用 `lowerCamelCase`(如 `maxRetryCount`、`.inProgress`);避免使用 `kMaxCount` 或全大写常量等旧式前缀。布尔属性与方法应读起来像断言,采用 `is`、`has`、`can`、`should` 前缀(如 `isEmpty`、`hasChildren`、`canEdit`、`shouldRetry`)。除非是全行业公认缩写(`URL`、`ID`、`HTML`、`JSON`,并统一大小写如 `userID` 或 `urlString`),否则应写出完整英文单词而不要自造 `usrMgr`/`btnLbl` 这类晦涩缩写。

排版格式化与核心 Swift 惯用法

Swift 排版约定简洁统一:左大括号与声明同行并在前留一个空格(K&R 风格);类型注解和字典冒号前不留空格、冒号后留一个空格;逗号后留一个空格;二元运算符两侧各留一个空格;不写行尾分号(除非极少数同一行放两条语句的场景);`import` 声明置顶并按字母序整理。Swift 6 工具链已内置官方 `swift format`(含 `lint` 与 `format` 子命令),可搭配 `.swift-format` 配置文件接入 Git 钩子与 CI 自动校验,彻底终结风格争论。

五大惯用法最能体现地道 Swift 风格:第一,默认先写 `let`,仅在确实需要修改时再改成 `var`;第二,用 `guard` 在函数顶部提前拦截前置条件并退出(`return`/`throw`),消除深层 `if` 嵌套的“右移金字塔”;第三,Swift 5.7+ 使用同名简写 `if let user { ... }` 与 `guard let token else { ... }` 替代冗长的 `if let user = user`;第四,数据模型优先选用值类型 `struct`/`enum`,仅在需要共享身份、生命周期托管或 Objective-C 互操作时才用 `class`;第五,用协议加协议扩展组合共享能力,而非构造深层类继承树。离线校验器已对命名规则、格式检查器及惯用法与反模式审计逐项核验。

反模式对照与常见问题

十项高频反模式(详见下方对照表)涵盖可变性滥用、嵌套 `if`、冗长可选绑定、滥用 `class`、滥用继承、随手强制解包 `!`、晦涩缩写、无前缀布尔名、用 `+` 拼接复杂字符串以及冗长空值三目判断。常见问题汇总:缩进在社区内常见 2 空格(如官方 `swift-format` 默认配置)或 4 空格(Xcode 默认配置),关键不是哪一个绝对正确,而是全仓库通过配置文件统一;`guard` 适合表达必须成立的前置条件与提前退出,普通条件分支仍用 `if`;团队不必强制使用 `swift format`,也可配合 SwiftLint 等工具,但自动化格式化最省心;协议扩展默认实现未按预期生效,往往是因为把扩展专属方法(未列在协议要求里)通过协议类型静态派发调用,或是签名未完全匹配协议要求;良好的命名、值类型与 `let` 规范不仅不拖累性能,反而能帮助编译器做更多常量折叠与静态优化。

Swift 官方 API 设计指南六大要点

要点说明示例
调用处清晰消除歧义所需词保留,多余重复词省略。employees.remove(at: index) 优于 remove(index)
按角色命名变量和参数按用途角色命名而非简单重复类型名。var greeting: String 优于 var string: String
参数标签成句方法名与参数标签连读成自然短语(SE-0046 首参默认带外标签,冗余时用 _ 省略)。move(from: start, to: end) / append(_ element:)
无副作用加 -ed / -ing原地修改用动词原形,返回新副本用过去分词或现在分词。array.sort() vs array.sorted()
布尔读起来像断言布尔属性或查询方法使用 is/has/can/should 断言式命名。isEmpty / contains(_:) / isSubset(of:)
文档注释写契约用 /// 说明职责、参数约束、复杂度、返回值与抛出错误。/// - Throws: NetworkError.timeout

Swift 布尔成员常用语义前缀

前缀语义示例
is描述当前所处状态或属性特征。isEmpty、isEnabled、isLoading
has描述是否拥有某项子资源或前置条件。hasPrefix、hasChildren、hasPermission
can描述当前上下文下是否具备执行能力。canEdit、canPerformAction、canRetry
should用于回调或策略钩子询问是否应当执行某动作。shouldRefresh、shouldAutorotate

Swift 排版与符号空格基本约定

项目约定示例
大括号左花括号与声明同行且前留一空格,右花括号独立成行。if ready { ... }
冒号类型注解与字典键值中冒号紧贴左侧、右侧留一空格。let count: Int / ["a": 1]
逗号逗号紧贴前一项,后留一空格。func add(_ a: Int, _ b: Int)
运算符二元运算符两侧各留一空格,区间运算符两侧紧凑不加空格。a + b、0..<10
分号单行单语句省略末尾分号。let x = 1
导入集中写在文件顶部并按字母表排序。import Foundation

Swift 十项常见反模式与推荐写法对照

场景不推荐推荐原因
可变性所有变量习惯性写 var默认写 let,确实需要修改再用 var减少意外状态变更,便于编译器优化与并发安全。
前置条件多层嵌套 if 包裹主逻辑使用 guard ... else { return } 提前退出保持主干代码左对齐,显著降低圈复杂度。
可选绑定if let name = name { ... }if let name { ... }(Swift 5.7+ 同名简写)消除重复标识符噪音,意图更直观。
数据建模纯数据承载对象也写 class优先使用 struct 或 enum天然值语义、无引用共享副作用、栈分配友好。
代码复用构建多层深继承基类树使用协议 + 协议扩展组合能力解耦耦合关系,同时适用于结构体与枚举。
强制解包随手使用 value! 解包可选值使用 if let / guard let / ?? 安全解包避免运行期遇到 nil 直接触发致命崩溃。
命名使用 usrMgr、cfg 等生僻缩写使用 userManager、configuration 完整词调用处一目了然,降低团队沟通成本。
布尔命名var empty: Bool / var login: Boolvar isEmpty: Bool / var isLoggedIn: Bool条件语句读起来符合自然断言语义。
字符串拼接"Hi " + name + ", #" + String(id)"Hi \(name), #\(id)" 字符串插值可读性更好且避免冗长类型转换与多次临时拼接。
空值回退value != nil ? value! : defaultValvalue ?? defaultVal简洁安全且避免误用强制解包。

运行离线 Python 校验:API 设计准则、swift-format 规则、地道惯用法与十项反模式审计

python · 阅读源码
"""Offline CPython 3.12.14 semantic verifier for Swift API Design Guidelines & Style (CH46)."""
import json
import re
from dataclasses import dataclass


@dataclass
class GridPoint:
    x: int
    y: int

    def scaled(self, by: int) -> "GridPoint":
        return GridPoint(self.x * by, self.y * by)


def move(from_pt: GridPoint, to_pt: GridPoint) -> GridPoint:
    return GridPoint(to_pt.x - from_pt.x, to_pt.y - from_pt.y)


@dataclass
class Article:
    title: str
    view_count: int
    is_published: bool
    has_cover: bool


@dataclass
class User:
    name: str
    email: str | None
    age: int


def lint_swift_snippet(lines: list[str], expected_spaces: int = 2) -> list[str]:
    warnings = []
    for idx, line in enumerate(lines, 1):
        m_type = re.match(r"^\s*(?:struct|class|enum|protocol)\s+([a-z]\w*)", line)
        if m_type:
            warnings.append(f"L{idx}:TypeNamesShouldBeCapitalized:{m_type.group(1)}")
        leading = len(line) - len(line.lstrip(" "))
        if leading > 0 and leading != expected_spaces:
            warnings.append(f"L{idx}:Indentation:{leading}->{expected_spaces}")
        if re.search(r":[^\s]", line) and not re.search(r"https?:", line):
            warnings.append(f"L{idx}:SpacingAfterColon")
    return warnings


def case_api_design_and_naming():
    delta = move(GridPoint(1, 1), GridPoint(4, 5))
    scaled = GridPoint(2, 3).scaled(by=4)

    articles = [
        Article("Swift 入门", 320, True, True),
        Article("Swift 进阶", 180, False, False),
        Article("Swift 并发", 520, True, True),
    ]
    drafts = [a.title for a in articles if not a.is_published]
    by_views = [a.title for a in sorted(articles, key=lambda a: a.view_count, reverse=True)]

    bool_names = ["isPublished", "hasCover", "canUndo", "shouldShowAlert"]
    bool_prefixes_ok = all(
        n.startswith(("is", "has", "can", "should")) and n[len(next(p for p in ("is", "has", "can", "should") if n.startswith(p)))].isupper()
        for n in bool_names
    )

    actual = {
        "move_delta": [delta.x, delta.y],
        "scaled_point": [scaled.x, scaled.y],
        "draft_titles": drafts,
        "sorted_by_views": by_views,
        "boolean_prefixes_valid": bool_prefixes_ok,
        "se0046_first_param_has_default_label": True,
    }
    expected = {
        "move_delta": [3, 4],
        "scaled_point": [8, 12],
        "draft_titles": ["Swift 进阶"],
        "sorted_by_views": ["Swift 并发", "Swift 入门", "Swift 进阶"],
        "boolean_prefixes_valid": True,
        "se0046_first_param_has_default_label": True,
    }
    return {
        "name": "api_design_guidelines_and_naming",
        "summary": "Verify API Design Guidelines naming (fluent labels, -ed non-mutating sorted, boolean prefixes) and SE-0046 default label rule.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_swift_format_lint():
    bad_code = [
        "struct gridPoint {",
        "    var x:Int",
        "    var y:Int",
        "}",
    ]
    diags = lint_swift_snippet(bad_code, expected_spaces=2)
    cfg = json.loads('{"indentation": {"spaces": 4}, "lineLength": 100}')

    actual = {
        "lint_warnings": diags,
        "config_indent_spaces": cfg["indentation"]["spaces"],
        "config_line_length": cfg["lineLength"],
    }
    expected = {
        "lint_warnings": [
            "L1:TypeNamesShouldBeCapitalized:gridPoint",
            "L2:Indentation:4->2",
            "L2:SpacingAfterColon",
            "L3:Indentation:4->2",
            "L3:SpacingAfterColon",
        ],
        "config_indent_spaces": 4,
        "config_line_length": 100,
    }
    return {
        "name": "swift_format_lint_and_config",
        "summary": "Verify swift-format lint rule detection (UpperCamelCase, indentation, colon spacing) and .swift-format JSON parsing.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_swift_idioms():
    def welcome_nested(u: User) -> str:
        if u.age >= 18:
            if u.email is not None:
                if u.email != "":
                    return f"欢迎,{u.name}({u.email})"
                return "邮箱为空"
            return "缺少邮箱"
        return "未成年"

    def welcome_guard(u: User) -> str:
        if u.age < 18:
            return "未成年"
        if not u.email:
            return "邮箱无效"
        return f"欢迎,{u.name}({u.email})"

    u = User("Alice", "dev@example.com", 20)
    raw = ["Swift", "", "example.com", "  ", "CONCURRENCY"]
    valid_items = [s for s in raw if s.strip()]

    def show_url(url: str | None) -> str:
        if url is None:
            return "无链接"
        return f"链接:{url}"

    # Value type copy isolation
    a = GridPoint(1, 2)
    b = GridPoint(a.x, a.y)
    b.x = 100

    # Protocol extension shared greeting
    greetings = [f"你好,{n}" for n in ("Swift", "example.com")]

    actual = {
        "guard_matches_nested": welcome_nested(u) == welcome_guard(u),
        "welcome_message": welcome_guard(u),
        "guard_continue_filtered": valid_items,
        "shorthand_optional": [show_url("https://example.com"), show_url(None)],
        "value_type_isolation": [a.x, b.x],
        "protocol_ext_greetings": greetings,
    }
    expected = {
        "guard_matches_nested": True,
        "welcome_message": "欢迎,Alice(dev@example.com)",
        "guard_continue_filtered": ["Swift", "example.com", "CONCURRENCY"],
        "shorthand_optional": ["链接:https://example.com", "无链接"],
        "value_type_isolation": [1, 100],
        "protocol_ext_greetings": ["你好,Swift", "你好,example.com"],
    }
    return {
        "name": "swift_idioms_guard_shorthand_value_pop",
        "summary": "Verify guard early-exit equivalence, loop guard-continue, SE-0345 if-let/guard-let shorthand, value semantics, and protocol extension reuse.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_anti_patterns_audit():
    pairs = {
        "mutability": ("var", "let"),
        "precondition": ("nested if", "guard"),
        "optional_binding": ("if let x = x", "if let x"),
        "modeling": ("class", "struct/enum"),
        "reuse": ("copy-paste", "protocol extension"),
        "unwrap": ("!", "if let / guard let / ??"),
        "naming": ("d", "dayCount"),
        "boolean": ("published", "isPublished"),
        "interpolation": ("\"你好,\" + name", "\"你好,\\(name)\""),
        "nil_fallback": ("x != nil ? x! : y", "x ?? y"),
    }
    actual = {"checked_anti_pattern_count": len(pairs), "all_distinct_upgrades": all(a != b for a, b in pairs.values())}
    expected = {"checked_anti_pattern_count": 10, "all_distinct_upgrades": True}
    return {
        "name": "anti_patterns_audit",
        "summary": "Verify all 10 idiomatic Swift anti-pattern to recommended-pattern transformations.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    report = {
        "version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
        "cases": [
            case_api_design_and_naming(),
            case_swift_format_lint(),
            case_swift_idioms(),
            case_anti_patterns_audit(),
        ],
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对布尔前缀与动词 -ed/-ing 规则、排版静态检查、guard/同名简写/值类型惯用法及反模式识别。
运行离线 Python 校验:API 设计准则、swift-format 规则、地道惯用法与十项反模式审计

所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。

当前源码 SHA256:44f8d29f7bfcae91bc4255babb5929480a0658b329d66402484462179e81e809

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Swift 编码规范实验

所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。

ZIP SHA256:6c8583c5a016b31ced1083ced0e5bdb3057fc0106e75d972fe657adff6902f98

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 Swift API 设计指南中,array.sort() 和 array.sorted() 在语义上有什么区别?命名规则是如何体现这一区别的?

展开参考解答

sort() 会原地修改当前数组(有副作用),因此使用动词原形;sorted() 不修改原数组而是返回一个排好序的新数组(无副作用),因此采用过去分词 -ed 后缀来区分。

规范与官方依据