swift-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSwift 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 in your Swift project:
.claude/mcps/swiftlens.jsonjson
{
"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 for complete setup guide, all 15 tools, index building, and usage examples.
references/swiftlens-mcp-claude-code.mdWorkflow: 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.jsonjson
{
"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
基本原则
- Clarity at point of use is paramount - evaluate designs by examining use cases, not just declarations
- Clarity over brevity - compact code comes from the type system, not minimal characters
- Write documentation for every public declaration - if you can't describe functionality simply, the API may be poorly designed
- Name by role, not type - not
var greeting = "Hello"var string = "Hello" - Favour elegance through simplicity - avoid over-engineering unless complexity genuinely warrants it
- 使用时的清晰度是首要原则——通过用例而非仅声明来评估设计
- 清晰度优先于简洁性——简洁代码应来自类型系统,而非最少字符数
- 为每个公共声明编写文档——如果你无法简单描述功能,说明API设计可能存在问题
- 按角色命名,而非类型——例如而非
var greeting = "Hello"var string = "Hello" - 通过简洁实现优雅——除非复杂度确实必要,否则避免过度工程化
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
- ensures UI-related code executes on the main thread
@MainActor - Global actor-isolated types are automatically
Sendable
Swift 6默认启用基于区域隔离(SE-0414)的完整并发检查。编译器现在可验证代码安全性,在编译时捕获真实并发问题的同时减少许多误报。
关键要点:
- Async ≠ 后台执行——async函数可挂起,但不会自动在后台线程运行
- Actors通过自动同步保护可变共享状态
- 确保UI相关代码在主线程执行
@MainActor - 全局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() } // Unnecessaryswift
// 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() } // UnnecessaryActor 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
需避免的常见陷阱
- Don't mark functions as unnecessarily - async calling convention has overhead
async - Never use with async/await - risk of deadlock
DispatchSemaphore - Don't create stateless actors - use non-isolated async functions instead
- Avoid split isolation - don't mix isolation domains within one type
- Check task cancellation - long operations must check
Task.checkCancellation() - Don't assume async means background - explicitly move work to background if needed
- Avoid excessive context switching - group operations within same isolation domain
- 不要不必要地将函数标记为——async调用约定存在性能开销
async - 切勿将与async/await混用——存在死锁风险
DispatchSemaphore - 不要创建无状态actors——改用非隔离async函数
- 避免拆分隔离——不要在一个类型中混合不同隔离域
- 检查任务取消——长时间操作必须调用
Task.checkCancellation() - 不要假设async意味着后台执行——如需后台执行需显式指定
- 避免过度上下文切换——将操作分组到相同隔离域内
API Design Quick Reference
API设计快速参考
Naming Conventions
命名规范
- Types/protocols:
UpperCamelCase - Everything else:
lowerCamelCase - Protocols describing capabilities: ,
-able,-iblesuffixes (-ing,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 cautionswift
static let config = Config() // 常量 - 合法
@MainActor static var state = State() // Actor隔离 - 合法
nonisolated(unsafe) var cache = [String: Data]() // 不安全 - 谨慎使用Other Changes
其他变更
- /
@UIApplicationMaindeprecated (use@NSApplicationMain)@main - required for existential types
any - 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:
- - Warning, allows usage
deprecated - - Error from specific version
obsoleted - - Error, completely prevents usage
unavailable
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
编写代码时
- Apply naming conventions following role-based, clarity-first principles
- Use appropriate isolation (for UI, actors for mutable state)
@MainActor - Implement async/await patterns correctly with proper cancellation handling
- Follow Swift 6 concurrency model - trust compiler's flow analysis
- Document public APIs with clear, concise summaries
- 遵循基于角色、清晰度优先的命名规范
- 使用适当的隔离机制(UI代码用,可变状态用actors)
@MainActor - 正确实现async/await模式并妥善处理取消
- 遵循Swift 6并发模型——信任编译器的流分析
- 为公共API编写清晰、简洁的文档
When Reviewing Code
审查代码时
- Check for concurrency safety violations
- Verify proper actor isolation and Sendable conformance
- Ensure async functions handle cancellation appropriately
- Validate API naming follows Swift guidelines
- Confirm availability annotations are correct for target platforms
- 检查并发安全违规
- 验证正确的actor隔离和Sendable一致性
- 确保async函数适当处理取消
- 确认API命名符合Swift指南
- 验证可用性注解与目标平台匹配
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 over
count(where:)filter().count - Use for fixed-size, performance-critical data
InlineArray - Trust compiler's concurrency flow analysis - avoid unnecessary conformances
Sendable
- 尽量减少注释——代码应尽可能自文档化
- 避免过度工程化和不必要的抽象
- 使用基于角色而非类型的有意义变量名
- 遵循已确立的项目架构与模式
- 优先使用而非
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 attribute usage, deprecation strategies, and platform version management
@available
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 for runtime platform detection
#available - Use for API availability marking
@available
- Swift 6.0+编译器以支持Swift 6特性
- Swift 6.2+以支持InlineArray及增强的并发特性
- macOS 15.7+及对应SDK
- iOS 18+以使用最新平台特性
- 使用进行运行时平台检测
#available - 使用标记API可用性
@available