claude-code/claude-zh/rules/swift/coding-style.md

48 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
paths:
- "**/*.swift"
- "**/Package.swift"
---
# Swift 程式碼風格 (Coding Style)
> 本檔案擴展了 [common/coding-style.md](../common/coding-style.md),包含 Swift 特定內容。
## 格式化 (Formatting)
- 使用 **SwiftFormat** 進行自動格式化,使用 **SwiftLint** 強制執行風格規範。
- `swift-format` 已與 Xcode 16+ 綁定,可作為替代方案。
## 不可變性 (Immutability)
- 優先使用 `let` 而非 `var` — 將所有內容定義為 `let`,只有在編譯器要求時才改為 `var`
- 預設使用具備值語義 (Value semantics) 的 `struct`;只有在需要標識 (Identity) 或引用語義 (Reference semantics) 時才使用 `class`
## 命名 (Naming)
遵循 [Apple API 設計指引 (Apple API Design Guidelines)](https://www.swift.org/documentation/api-design-guidelines/)
- 使用處應清晰明確 — 省略不必要的詞彙。
- 根據角色命名方法與屬性,而非根據型別。
- 對於常數,優先使用 `static let` 而非全域常數。
## 錯誤處理 (Error Handling)
使用型別化抛出 (Typed throws, Swift 6+) 與模式匹配 (Pattern matching)
```swift
func load(id: String) throws(LoadError) -> Item {
guard let data = try? read(from: path) else {
throw .fileNotFound(id)
}
return try decode(data)
}
```
## 併發 (Concurrency)
啟用 Swift 6 嚴格併發檢查。優先使用:
- 跨越隔離邊界的數據使用 `Sendable` 值型別。
- 共享的可變狀態使用 Actors。
- 優先使用結構化併發 (`async let`, `TaskGroup`),而非非結構化的 `Task {}`