coding-standards-enforcer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCoding Standards Enforcer
编码标准强制执行工具
Description and Goals
描述与目标
This skill enforces repository-wide coding standards for Swift 6.2 concurrency, Swift language rules, and best practices. It ensures all Swift code in the repository follows consistent patterns, uses modern Swift APIs, and adheres to strict concurrency requirements.
本技能用于在仓库范围内强制执行Swift 6.2并发机制、Swift语言规则及最佳实践的编码标准。确保仓库中所有Swift代码遵循一致的模式,使用现代Swift API,并符合严格的并发要求。
Goals
目标
- Ensure compliance with Swift 6.2 strict concurrency rules
- Enforce modern Swift language patterns and APIs
- Prevent common concurrency mistakes and anti-patterns
- Maintain consistent code style across the repository
- Support Swift 6 migration and best practices
- 确保符合Swift 6.2严格并发规则
- 推行现代Swift语言模式与API
- 预防常见的并发错误与反模式
- 维护仓库内代码风格的一致性
- 支持Swift 6迁移及最佳实践
What This Skill Should Do
本技能的适用场景
When reviewing or implementing Swift code changes, this skill should:
- Enforce concurrency rules - Ensure all code follows Swift 6.2 strict concurrency requirements
- Check language standards - Verify use of modern Swift APIs and patterns
- Identify violations - Scan for common mistakes and anti-patterns
- Suggest fixes - Provide guidance on how to correct violations
- Maintain consistency - Ensure code follows repository-wide standards
Use this skill whenever you add, modify, or review Swift code in this repo.
在审查或实现Swift代码变更时,本技能应:
- 强制执行并发规则 - 确保所有代码遵循Swift 6.2严格并发要求
- 检查语言标准 - 验证是否使用现代Swift API与模式
- 识别违规情况 - 扫描常见错误与反模式
- 提供修复建议 - 指导如何修正违规问题
- 保持一致性 - 确保代码符合仓库范围内的标准
每当你在本仓库中添加、修改或审查Swift代码时,都应使用本技能。
Information About the Skill
技能相关信息
Workflow
工作流程
- Identify the files and changes in scope.
- Scan for violations of the rules below.
- Apply fixes or call out deviations explicitly.
- 确定涉及的文件与变更范围。
- 扫描是否存在以下规则的违规情况。
- 应用修复或明确指出偏差。
Swift Concurrency Guidelines
Swift并发指南
Core Mental Model
核心思维模型
Think in isolation domains rather than threads:
- is the UI lane and must own UI state.
MainActor - types protect their own mutable state.
actor - code is shared and cannot touch actor state.
nonisolated - types are safe to move across domains.
Sendable
以隔离域而非线程的角度思考:
- 是UI专用通道,必须拥有UI状态。
MainActor - 类型保护自身的可变状态。
actor - 代码是共享的,不能访问actor状态。
nonisolated - 类型可安全跨域传递。
Sendable
Strict Concurrency
严格并发
Swift 6.2 defaults to isolation for Views and UI logic. Assume strict isolation checks are active. Everything is by default.
@MainActor@MainActorSwift 6.2默认对视图和UI逻辑采用隔离。假设严格隔离检查已启用,所有内容默认均为。
@MainActor@MainActorAsync and Parallel Work
异步与并行工作
swift
func fetchUser(id: Int) async throws -> User {
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}
async let avatar = fetchImage("avatar.jpg")
async let banner = fetchImage("banner.jpg")
let profile = Profile(avatar: try await avatar, banner: try await banner)swift
func fetchUser(id: Int) async throws -> User {
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}
async let avatar = fetchImage("avatar.jpg")
async let banner = fetchImage("banner.jpg")
let profile = Profile(avatar: try await avatar, banner: try await banner)Tasks and Task Groups
任务与任务组
swift
.task { avatar = await downloadAvatar() }
Task { await saveProfile() }
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask { avatar = try await downloadAvatar() }
group.addTask { bio = try await fetchBio() }
try await group.waitForAll()
}swift
.task { avatar = await downloadAvatar() }
Task { await saveProfile() }
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask { avatar = try await downloadAvatar() }
group.addTask { bio = try await fetchBio() }
try await group.waitForAll()
}Isolation Domains
隔离域
swift
@MainActor
final class ViewModel {
var items: [Item] = []
}
actor BankAccount {
var balance: Double = 0
func deposit(_ amount: Double) { balance += amount }
}swift
@MainActor
final class ViewModel {
var items: [Item] = []
}
actor BankAccount {
var balance: Double = 0
func deposit(_ amount: Double) { balance += amount }
}Approachable Concurrency Settings (Swift 6.2+)
易用并发设置(Swift 6.2+)
- keeps UI code on the main actor by default.
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor - keeps nonisolated async on the caller's actor.
SWIFT_APPROACHABLE_CONCURRENCY = YES
swift
@concurrent func processLargeFile() async { }- 使UI代码默认在主actor上运行。
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor - 使非隔离异步代码在调用者的actor上运行。
SWIFT_APPROACHABLE_CONCURRENCY = YES
swift
@concurrent func processLargeFile() async { }Sendable
Sendable类型
swift
struct User: Sendable {
let id: Int
let name: String
}
final class ThreadSafeCache: @unchecked Sendable {
private let lock = NSLock()
private var storage: [String: Data] = [:]
}swift
struct User: Sendable {
let id: Int
let name: String
}
final class ThreadSafeCache: @unchecked Sendable {
private let lock = NSLock()
private var storage: [String: Data] = [:]
}Isolation Inheritance
隔离继承
- inherits the current actor.
Task { } - does not inherit isolation and should be rare.
Task.detached { }
- 继承当前actor。
Task { } - 不继承隔离,应尽量少用。
Task.detached { }
Background Tasks
后台任务
Move heavy physics/data work off the main actor using functions or dedicated actors.
@concurrent使用函数或专用actor将繁重的物理/数据处理工作移出主actor。
@concurrentTask Management
任务管理
Cancel long-running tasks on teardown.
在销毁时取消长时间运行的任务。
Common Mistakes to Avoid
需避免的常见错误
- Treating as automatic background work.
async - Creating many actors when is sufficient.
@MainActor - Using when the enclosing function can be annotated.
MainActor.run - Blocking async code with or
DispatchSemaphore.DispatchGroup.wait() - Spawning unstructured instances instead of
Taskor task groups.async let
- 将视为自动后台工作。
async - 在足够的情况下创建大量actor。
@MainActor - 在封闭函数可添加注解时使用。
MainActor.run - 使用或
DispatchSemaphore阻塞异步代码。DispatchGroup.wait() - 生成非结构化实例而非使用
Task或任务组。async let
Quick Reference
快速参考
- and
asyncfor suspension points.await - for structured async work.
Task { } - for isolated mutable state.
actor - for cross-actor data transfer.
Sendable
- 与
async用于挂起点。await - 用于结构化异步工作。
Task { } - 用于隔离可变状态。
actor - 用于跨actor数据传输。
Sendable
Swift Language Standards
Swift语言标准
Observable Classes
可观察类
@Observable@MainActor@MainActor@Observable@MainActor@MainActorObservation vs Combine
观察机制 vs Combine
- Prefer +
@Observablefor reference-type models.@State - Avoid ,
ObservableObject, and@StateObjectunless interacting with legacy code that still requires Combine.@ObservedObject
- 优先为引用类型模型使用+
@Observable。@State - 除非与仍需使用Combine的遗留代码交互,否则应避免使用、
ObservableObject和@StateObject。@ObservedObject
Swift-Native APIs
Swift原生API
Prefer Swift-native alternatives to Foundation methods where they exist, such as using with strings rather than .
replacing("hello", with: "world")replacingOccurrences(of: "hello", with: "world")在有替代方案的情况下,优先使用Swift原生API而非Foundation方法,例如对字符串使用而非。
replacing("hello", with: "world")replacingOccurrences(of: "hello", with: "world")Modern Foundation API
现代Foundation API
Prefer modern Foundation API, for example to find the app's documents directory, and to append strings to a URL.
URL.documentsDirectoryappending(path:)优先使用现代Foundation API,例如使用查找应用的文档目录,使用将字符串追加到URL。
URL.documentsDirectoryappending(path:)Number Formatting
数字格式化
Never use C-style number formatting such as ; always use instead.
Text(String(format: "%.2f", abs(myNumber)))Text(abs(change), format: .number.precision(.fractionLength(2)))绝不要使用C风格的数字格式化,如;应始终使用替代。
Text(String(format: "%.2f", abs(myNumber)))Text(abs(change), format: .number.precision(.fractionLength(2)))Static Member Lookup
静态成员查找
Prefer static member lookup to struct instances where possible, such as rather than , and rather than .
.circleCircle().borderedProminentBorderedProminentButtonStyle()尽可能优先使用静态成员查找而非结构体实例,例如使用而非,使用而非。
.circleCircle().borderedProminentBorderedProminentButtonStyle()Modern Concurrency
现代并发机制
Never use old-style Grand Central Dispatch concurrency such as . If behavior like this is needed, always use modern Swift concurrency.
DispatchQueue.main.async()绝不要使用旧式Grand Central Dispatch并发机制,如。如果需要类似行为,应始终使用现代Swift并发机制。
DispatchQueue.main.async()Text Filtering
文本过滤
Filtering text based on user-input must be done using as opposed to .
localizedStandardContains()contains()基于用户输入的文本过滤必须使用而非。
localizedStandardContains()contains()Force Unwraps
强制解包
Avoid force unwraps and force unless it is unrecoverable.
try除非是不可恢复的情况,否则应避免强制解包和强制。
try