关于 swift-expert
面向 Swift 应用开发的技能,强调类型安全、面向协议的设计、async/await 和值语义,并提供架构、并发、性能与测试指南。
主要功能
- 01面向协议的 API 设计
- 02async/await 与 Actor 指南
- 03SwiftUI 状态管理
- 04使用 Instruments 分析性能
- 05XCTest 与异步测试
适用场景
- 01设计可复用的 Swift API
- 02使用 Actor 安全处理共享状态
- 03验证构建结果与异步测试
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jeffallan/ claude-skills --skill swift-expert安装后在 Claude Code 中输入/swift-expert确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/async-concurrency.mdmemory-performance.mdprotocol-oriented.mdswiftui-patterns.mdtesting-patterns.md详细介绍
Swift 专家
核心工作流
- 架构分析 - 确定平台目标、依赖项和设计模式
- 设计协议 - 创建以协议为先、包含关联类型的 API
- 实现 - 使用 async/await 和值语义编写类型安全的代码
- 优化 - 使用 Instruments 进行性能分析,确保线程安全
- 测试 - 使用 XCTest 和异步模式编写全面的测试
验证检查点: 第 3 步后,运行
swift build验证编译。第 4 步后,运行swift build -warnings-as-errors,以发现 actor 隔离和 Sendable 警告。第 5 步后,运行swift test并确认所有异步测试均通过。
参考指南
根据上下文加载详细指南:
| 主题 | 参考资料 | 加载时机 |
|---|---|---|
| SwiftUI | references/swiftui-patterns.md | 构建视图、管理状态、使用修饰器时 |
| 并发 | references/async-concurrency.md | 使用 async/await、actor、结构化并发时 |
| 协议 | references/protocol-oriented.md | 设计协议、使用泛型和类型擦除时 |
| 内存 | references/memory-performance.md | 使用 ARC、weak/unowned、优化性能时 |
| 测试 | references/testing-patterns.md | 使用 XCTest、编写异步测试、制定模拟策略时 |
代码模式
async/await — 正确与错误示例
// ✅ DO: async/await with structured error handling
func fetchUser(id: String) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}
// ❌ DON'T: mixing completion handlers with async context
func fetchUser(id: String) async throws -> User {
return try await withCheckedThrowingContinuation { continuation in
// Avoid wrapping existing async APIs this way when a native async version exists
legacyFetch(id: id) { result in
continuation.resume(with: result)
}
}
}
SwiftUI 状态管理
// ✅ DO: use @Observable (Swift 5.9+) for view models
@Observable
final class CounterViewModel {
var count = 0
func increment() { count += 1 }
}
struct CounterView: View {
@State private var vm = CounterViewModel()
var body: some View {
VStack {
Text("\(vm.count)")
Button("Increment", action: vm.increment)
}
}
}
// ❌ DON'T: reach for ObservableObject/Published when @Observable suffices
class LegacyViewModel: ObservableObject {
@Published var count = 0 // Unnecessary boilerplate in Swift 5.9+
}
面向协议的架构
// ✅ DO: define capability protocols with associated types
protocol Repository<Entity> {
associatedtype Entity: Identifiable
func fetch(id: Entity.ID) async throws -> Entity
func save(_ entity: Entity) async throws
}
struct UserRepository: Repository {
typealias Entity = User
func fetch(id: UUID) async throws -> User { /* … */ }
func save(_ user: User) async throws { /* … */ }
}
// ❌ DON'T: use classes as base types when a protocol fits
class BaseRepository { // Avoid class inheritance for shared behavior
func fetch(id: UUID) async throws -> Any { fatalError("Override required") }
}
用于线程安全的 Actor
// ✅ DO: isolate mutable shared state in an actor
actor ImageCache {
private var cache: [URL: UIImage] = [:]
func image(for url: URL) -> UIImage? { cache[url] }
func store(_ image: UIImage, for url: URL) { cache[url] = image }
}
// ❌ DON'T: use a class with manual locking
class UnsafeImageCache {
private var cache: [URL: UIImage] = [:]
private let lock = NSLock() // Error-prone; prefer actor isolation
func image(for url: URL) -> UIImage? {
lock.lock(); defer { lock.unlock() }
return cache[url]
}
}
约束
必须做到
- 适当使用类型提示和类型推断
- 遵循 Swift API 设计指南
- 对异步操作使用
async/await(参见上面的模式) - 确保符合并发要求的
Sendable约束 - 默认使用值类型(
struct/enum) - 使用标记注释(
/// …)为 API 编写文档 - 使用属性包装器处理横切关注点
- 优化前先使用 Instruments 进行性能分析
绝不能做
- 无正当理由使用强制解包(
!) - 在闭包中创建保留环
- 不恰当地混合同步和异步代码
- 忽略 actor 隔离警告
- 不必要地使用隐式解包可选项
- 跳过错误处理
- 存在 Swift 替代方案时仍使用 Objective-C 模式
- 硬编码特定平台的值
输出模板
实现 Swift 功能时,请提供:
- 协议定义和类型别名
- 模型类型(具有值语义的结构体/类)
- 视图实现(SwiftUI)或视图控制器
- 展示用法的测试
- 对架构决策的简要说明
由 @jeffallan(Synergetic Solutions 首席顾问)维护
评论
支持 Markdown