swift-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Swift Best Practices Skill

Swift最佳实践技能

Overview

概述

Apply modern Swift development best practices focusing on Swift 6+ features, concurrency safety, API design principles, and code quality guidelines for iOS and macOS projects targeting macOS 15.7+.
针对目标为macOS 15.7+的iOS和macOS项目,应用以Swift 6+特性、并发安全、API设计原则及代码质量指南为核心的现代Swift开发最佳实践。

When to Use This Skill

何时使用本技能

Use this skill when:
  • Writing new Swift code for iOS or macOS applications
  • Reviewing Swift code for correctness, safety, and style
  • Implementing Swift concurrency features (async/await, actors, MainActor)
  • Designing Swift APIs and public interfaces
  • Migrating code from Swift 5 to Swift 6
  • Addressing concurrency warnings, data race issues, or compiler errors related to Sendable/isolation
  • Working with modern Swift language features introduced in Swift 6 and 6.2
在以下场景使用本技能:
  • 为iOS或macOS应用编写新的Swift代码
  • 审查Swift代码的正确性、安全性和风格
  • 实现Swift并发特性(async/await、actors、MainActor)
  • 设计Swift API及公共接口
  • 将代码从Swift 5迁移至Swift 6
  • 解决与Sendable/隔离相关的并发警告、数据竞争问题或编译器错误
  • 使用Swift 6及6.2中引入的现代Swift语言特性

SwiftLens MCP Integration (Claude Code)

SwiftLens MCP集成(Claude Code)

This skill complements SwiftLens MCP server for semantic-level Swift code analysis.
What SwiftLens Provides:
  • 15 tools for semantic Swift analysis using Apple's SourceKit-LSP
  • Symbol lookup, cross-file references, type information
  • Safe code modification and refactoring
  • Compiler-grade understanding of Swift code structure
What This Skill Provides:
  • Swift 6+ design patterns and best practices
  • Concurrency strategies (async/await, actors, MainActor)
  • API design guidelines and naming conventions
  • Migration guidance (Swift 5 → Swift 6)
Setup for Claude Code CLI:
Create
.claude/mcps/swiftlens.json
in your Swift project:
json
{
  "mcpServers": {
    "swiftlens": {
      "description": "SwiftLens MCP provides semantic Swift analysis via SourceKit-LSP",
      "command": "uvx",
      "args": ["swiftlens"]
    }
  }
}
⚠️ Note: This is Claude Code configuration (not Claude Desktop). See
references/swiftlens-mcp-claude-code.md
for complete setup guide, all 15 tools, index building, and usage examples.
Workflow: SwiftLens provides runtime analysis (what the code is doing), this skill provides design expertise (what the code should be doing).
本技能可与SwiftLens MCP服务器配合使用,实现语义层面的Swift代码分析。
SwiftLens提供的功能:
  • 15个基于Apple SourceKit-LSP的语义Swift分析工具
  • 符号查找、跨文件引用、类型信息
  • 安全的代码修改与重构
  • 编译器级别的Swift代码结构理解
本技能提供的内容:
  • Swift 6+设计模式与最佳实践
  • 并发策略(async/await、actors、MainActor)
  • API设计指南与命名规范
  • 迁移指导(Swift 5 → Swift 6)
Claude Code CLI设置:
在你的Swift项目中创建
.claude/mcps/swiftlens.json
文件:
json
{
  "mcpServers": {
    "swiftlens": {
      "description": "SwiftLens MCP provides semantic Swift analysis via SourceKit-LSP",
      "command": "uvx",
      "args": ["swiftlens"]
    }
  }
}
⚠️ 注意:这是Claude Code的配置(而非Claude Desktop)。完整的设置指南、全部15个工具、索引构建及使用示例请参考
references/swiftlens-mcp-claude-code.md
工作流:SwiftLens提供运行时分析(代码当前的行为),本技能提供设计专业指导(代码应有的行为)。

Core Guidelines

核心指南

Fundamental Principles

基本原则

  1. Clarity at point of use is paramount - evaluate designs by examining use cases, not just declarations
  2. Clarity over brevity - compact code comes from the type system, not minimal characters
  3. Write documentation for every public declaration - if you can't describe functionality simply, the API may be poorly designed
  4. Name by role, not type -
    var greeting = "Hello"
    not
    var string = "Hello"
  5. Favour elegance through simplicity - avoid over-engineering unless complexity genuinely warrants it
  1. 使用时的清晰度是首要原则——通过用例而非仅声明来评估设计
  2. 清晰度优先于简洁性——简洁代码应来自类型系统,而非最少字符数
  3. 为每个公共声明编写文档——如果你无法简单描述功能,说明API设计可能存在问题
  4. 按角色命名,而非类型——例如
    var greeting = "Hello"
    而非
    var string = "Hello"
  5. 通过简洁实现优雅——除非复杂度确实必要,否则避免过度工程化

Swift 6 Concurrency Model

Swift 6并发模型

Swift 6 enables complete concurrency checking by default with region-based isolation (SE-0414). The compiler now proves code safety, eliminating many false positives whilst catching real concurrency issues at compile time.
Critical understanding:
  • Async ≠ background - async functions can suspend but don't automatically run on background threads
  • Actors protect mutable shared state through automatic synchronisation
  • @MainActor
    ensures UI-related code executes on the main thread
  • Global actor-isolated types are automatically
    Sendable
Swift 6默认启用基于区域隔离(SE-0414)的完整并发检查。编译器现在可验证代码安全性,在编译时捕获真实并发问题的同时减少许多误报。
关键要点:
  • Async ≠ 后台执行——async函数可挂起,但不会自动在后台线程运行
  • Actors通过自动同步保护可变共享状态
  • @MainActor
    确保UI相关代码在主线程执行
  • 全局actor隔离的类型自动具备
    Sendable
    特性

Essential Patterns

核心模式

Async/Await

Async/Await

swift
// Parallel execution with async let
func fetchData() async -> (String, Int) {
    async let stringData = fetchString()
    async let intData = fetchInt()
    return await (stringData, intData)
}

// Always check cancellation in long-running operations
func process(_ items: [Item]) async throws -> [Result] {
    var results: [Result] = []
    for item in items {
        try Task.checkCancellation()
        results.append(await process(item))
    }
    return results
}
swift
// Parallel execution with async let
func fetchData() async -> (String, Int) {
    async let stringData = fetchString()
    async let intData = fetchInt()
    return await (stringData, intData)
}

// Always check cancellation in long-running operations
func process(_ items: [Item]) async throws -> [Result] {
    var results: [Result] = []
    for item in items {
        try Task.checkCancellation()
        results.append(await process(item))
    }
    return results
}

MainActor for UI Code

用于UI代码的MainActor

swift
// Apply at type level for consistent isolation
@MainActor
class ContentViewModel: ObservableObject {
    @Published var images: [UIImage] = []

    func fetchData() async throws {
        self.images = try await fetchImages()
    }
}

// Avoid MainActor.run when direct await works
await doMainActorStuff()  // Good
await MainActor.run { doMainActorStuff() }  // Unnecessary
swift
// Apply at type level for consistent isolation
@MainActor
class ContentViewModel: ObservableObject {
    @Published var images: [UIImage] = []

    func fetchData() async throws {
        self.images = try await fetchImages()
    }
}

// Avoid MainActor.run when direct await works
await doMainActorStuff()  // Good
await MainActor.run { doMainActorStuff() }  // Unnecessary

Actor Isolation

Actor隔离

swift
actor DataCache {
    private var cache: [String: Data] = [:]

    func store(_ data: Data, forKey key: String) {
        cache[key] = data  // No await needed inside actor
    }

    nonisolated func cacheType() -> String {
        return "DataCache"  // No await needed - doesn't access isolated state
    }
}
swift
actor DataCache {
    private var cache: [String: Data] = [:]

    func store(_ data: Data, forKey key: String) {
        cache[key] = data  // No await needed inside actor
    }

    nonisolated func cacheType() -> String {
        return "DataCache"  // No await needed - doesn't access isolated state
    }
}

Common Pitfalls to Avoid

需避免的常见陷阱

  1. Don't mark functions as
    async
    unnecessarily
    - async calling convention has overhead
  2. Never use
    DispatchSemaphore
    with async/await
    - risk of deadlock
  3. Don't create stateless actors - use non-isolated async functions instead
  4. Avoid split isolation - don't mix isolation domains within one type
  5. Check task cancellation - long operations must check
    Task.checkCancellation()
  6. Don't assume async means background - explicitly move work to background if needed
  7. Avoid excessive context switching - group operations within same isolation domain
  1. 不要不必要地将函数标记为
    async
    ——async调用约定存在性能开销
  2. 切勿将
    DispatchSemaphore
    与async/await混用
    ——存在死锁风险
  3. 不要创建无状态actors——改用非隔离async函数
  4. 避免拆分隔离——不要在一个类型中混合不同隔离域
  5. 检查任务取消——长时间操作必须调用
    Task.checkCancellation()
  6. 不要假设async意味着后台执行——如需后台执行需显式指定
  7. 避免过度上下文切换——将操作分组到相同隔离域内

API Design Quick Reference

API设计快速参考

Naming Conventions

命名规范

  • Types/protocols:
    UpperCamelCase
  • Everything else:
    lowerCamelCase
  • Protocols describing capabilities:
    -able
    ,
    -ible
    ,
    -ing
    suffixes (
    Equatable
    ,
    ProgressReporting
    )
  • Factory methods: Begin with
    make
    (
    x.makeIterator()
    )
  • Mutating pairs: imperative vs past participle (
    x.sort()
    /
    x.sorted()
    )
  • 类型/协议:
    UpperCamelCase
  • 其他所有元素:
    lowerCamelCase
  • 描述能力的协议:使用
    -able
    -ible
    -ing
    后缀(如
    Equatable
    ProgressReporting
  • 工厂方法:以
    make
    开头(如
    x.makeIterator()
  • 可变方法对:命令式动词 vs 过去分词(如
    x.sort()
    /
    x.sorted()

Method Naming by Side Effects

按副作用区分方法命名

  • No side effects: Noun phrases (
    x.distance(to: y)
    )
  • With side effects: Imperative verbs (
    x.append(y)
    ,
    x.sort()
    )
  • 无副作用:名词短语(如
    x.distance(to: y)
  • 有副作用:命令式动词(如
    x.append(y)
    x.sort()

Argument Labels

参数标签

  • Omit when arguments can't be distinguished:
    min(number1, number2)
  • Value-preserving conversions omit first label:
    Int64(someUInt32)
  • Prepositional phrases label at preposition:
    x.removeBoxes(havingLength: 12)
  • Label all other arguments
  • 当参数无法区分时省略标签:
    min(number1, number2)
  • 保留值的转换省略第一个标签:
    Int64(someUInt32)
  • 介词短语标签放在介词位置:
    x.removeBoxes(havingLength: 12)
  • 为所有其他参数添加标签

Swift 6 Breaking Changes

Swift 6破坏性变更

Must Explicitly Mark Types with @MainActor (SE-0401)

必须使用@MainActor显式标记类型(SE-0401)

Property wrappers no longer infer actor isolation automatically.
swift
@MainActor
struct LogInView: View {
    @StateObject private var model = ViewModel()
}
属性包装器不再自动推断actor隔离。
swift
@MainActor
struct LogInView: View {
    @StateObject private var model = ViewModel()
}

Global Variables Must Be Concurrency-Safe (SE-0412)

全局变量必须具备并发安全性(SE-0412)

swift
static let config = Config()  // Constant - OK
@MainActor static var state = State()  // Actor-isolated - OK
nonisolated(unsafe) var cache = [String: Data]()  // Unsafe - use with caution
swift
static let config = Config()  // 常量 - 合法
@MainActor static var state = State()  // Actor隔离 - 合法
nonisolated(unsafe) var cache = [String: Data]()  // 不安全 - 谨慎使用

Other Changes

其他变更

  • @UIApplicationMain
    /
    @NSApplicationMain
    deprecated (use
    @main
    )
  • any
    required for existential types
  • Import visibility requires explicit access control
  • @UIApplicationMain
    /
    @NSApplicationMain
    已弃用(改用
    @main
  • 存在类型必须使用
    any
    关键字
  • 导入可见性需要显式访问控制

API Availability Patterns

API可用性模式

swift
// Basic availability
@available(macOS 15, iOS 18, *)
func modernAPI() { }

// Deprecation with message
@available(*, deprecated, message: "Use newMethod() instead")
func oldMethod() { }

// Renaming with auto-fix
@available(*, unavailable, renamed: "newMethod")
func oldMethod() { }

// Runtime checking
if #available(iOS 18, *) {
    // iOS 18+ code
}

// Inverted checking (Swift 5.6+)
if #unavailable(iOS 18, *) {
    // iOS 17 and lower
}
Key differences:
  • deprecated
    - Warning, allows usage
  • obsoleted
    - Error from specific version
  • unavailable
    - Error, completely prevents usage
swift
// Basic availability
@available(macOS 15, iOS 18, *)
func modernAPI() { }

// Deprecation with message
@available(*, deprecated, message: "Use newMethod() instead")
func oldMethod() { }

// Renaming with auto-fix
@available(*, unavailable, renamed: "newMethod")
func oldMethod() { }

// Runtime checking
if #available(iOS 18, *) {
    // iOS 18+ code
}

// Inverted checking (Swift 5.6+)
if #unavailable(iOS 18, *) {
    // iOS 17 and lower
}
关键区别:
  • deprecated
    - 警告,允许使用
  • obsoleted
    - 从特定版本开始报错
  • unavailable
    - 报错,完全禁止使用

How to Use This Skill

如何使用本技能

When Writing Code

编写代码时

  1. Apply naming conventions following role-based, clarity-first principles
  2. Use appropriate isolation (
    @MainActor
    for UI, actors for mutable state)
  3. Implement async/await patterns correctly with proper cancellation handling
  4. Follow Swift 6 concurrency model - trust compiler's flow analysis
  5. Document public APIs with clear, concise summaries
  1. 遵循基于角色、清晰度优先的命名规范
  2. 使用适当的隔离机制(UI代码用
    @MainActor
    ,可变状态用actors)
  3. 正确实现async/await模式并妥善处理取消
  4. 遵循Swift 6并发模型——信任编译器的流分析
  5. 为公共API编写清晰、简洁的文档

When Reviewing Code

审查代码时

  1. Check for concurrency safety violations
  2. Verify proper actor isolation and Sendable conformance
  3. Ensure async functions handle cancellation appropriately
  4. Validate API naming follows Swift guidelines
  5. Confirm availability annotations are correct for target platforms
  1. 检查并发安全违规
  2. 验证正确的actor隔离和Sendable一致性
  3. 确保async函数适当处理取消
  4. 确认API命名符合Swift指南
  5. 验证可用性注解与目标平台匹配

Code Quality Standards

代码质量标准

  • Minimise comments - code should be self-documenting where possible
  • Avoid over-engineering and unnecessary abstractions
  • Use meaningful variable names based on role, not type
  • Follow established project architecture and patterns
  • Prefer
    count(where:)
    over
    filter().count
  • Use
    InlineArray
    for fixed-size, performance-critical data
  • Trust compiler's concurrency flow analysis - avoid unnecessary
    Sendable
    conformances
  • 尽量减少注释——代码应尽可能自文档化
  • 避免过度工程化和不必要的抽象
  • 使用基于角色而非类型的有意义变量名
  • 遵循已确立的项目架构与模式
  • 优先使用
    count(where:)
    而非
    filter().count
  • 对固定大小、性能关键的数据使用
    InlineArray
  • 信任编译器的并发流分析——避免不必要的
    Sendable
    一致性声明

Resources

资源

references/

references/

Detailed reference material to load when in-depth information is needed:
  • swiftlens-mcp-claude-code.md - SwiftLens MCP server setup for Claude Code CLI, 15 semantic analysis tools, index building, usage examples, and integration workflows
  • api-design.md - Complete API design conventions, documentation standards, parameter guidelines, and naming patterns
  • concurrency.md - Detailed async/await patterns, actor best practices, common pitfalls, performance considerations, and thread safety patterns
  • swift6-features.md - New language features in Swift 6/6.2, breaking changes, migration strategies, and modern patterns
  • availability-patterns.md - Comprehensive
    @available
    attribute usage, deprecation strategies, and platform version management
Load these references when detailed information is needed beyond the core guidelines provided above.
需要深入信息时可加载以下详细参考资料:
  • swiftlens-mcp-claude-code.md - 适用于Claude Code CLI的SwiftLens MCP服务器设置、15个语义分析工具、索引构建、使用示例及集成工作流
  • api-design.md - 完整的API设计规范、文档标准、参数指南及命名模式
  • concurrency.md - 详细的async/await模式、actor最佳实践、常见陷阱、性能考量及线程安全模式
  • swift6-features.md - Swift 6/6.2中的新语言特性、破坏性变更、迁移策略及现代模式
  • availability-patterns.md - 全面的
    @available
    属性用法、弃用策略及平台版本管理
加载这些参考资料可获取上述核心指南之外的详细信息。

Platform Requirements

平台要求

  • Swift 6.0+ compiler for Swift 6 features
  • Swift 6.2+ for InlineArray and enhanced concurrency features
  • macOS 15.7+ with appropriate SDK
  • iOS 18+ for latest platform features
  • Use
    #available
    for runtime platform detection
  • Use
    @available
    for API availability marking
  • Swift 6.0+编译器以支持Swift 6特性
  • Swift 6.2+以支持InlineArray及增强的并发特性
  • macOS 15.7+及对应SDK
  • iOS 18+以使用最新平台特性
  • 使用
    #available
    进行运行时平台检测
  • 使用
    @available
    标记API可用性