关于 swift-library-design
面向 Swift 开发者的库与框架设计技能,涵盖协议导向 API、编译期安全、性能及结果构建器等模式。
主要功能
- 01协议导向的 API 设计
- 02编译期安全模式
- 03性能优化 API 指引
- 04结果构建器与 DSL 模式
- 05构建器及错误处理参考
适用场景
- 01设计可复用的 Swift 库 API
- 02构建类型安全的框架
- 03使用结果构建器创建 DSL
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ wendylabsinc/ claude-skills --skill swift-library-design安装后在 Claude Code 中输入/swift-library-design确认已加载。
附带文件references/api-patterns.mdreferences/performance.md
详细介绍
Swift 库设计
设计高质量 Swift 库和框架的模式与最佳实践。
核心原则
1. 面向协议的设计
围绕带有关联类型的协议进行设计,以提高灵活性和可测试性。使用泛型确保类型安全,并通过运行时多态提升灵活性。
2. 编译时安全
利用 Swift 的类型系统在编译时捕获错误。使用不可复制类型、泛型和协议约束,让无效状态无法表示。
3. 默认高性能
设计默认高效的 API。在热点路径使用 @inlinable,避免不必要的分配,并提供零拷贝选项。
4. 渐进式呈现
简单的事情应该简单,复杂的事情也应该能够实现。提供合理的默认值,同时允许自定义。
关键模式
带有关联类型的协议
public protocol Handler<Context>: Sendable {
associatedtype Context
func handle(input: Input, context: Context) async throws -> Output
}
// Consumers accept any conforming type
public struct Pipeline<Context> {
public func add<H: Handler>(handler: H) where H.Context == Context {
// Type-safe composition
}
}
ResponseGenerator 模式
允许多种返回类型并自动转换:
public protocol ResponseGenerator: Sendable {
func response(from request: Request, context: some RequestContext) throws -> Response
}
// Extend standard types
extension String: ResponseGenerator {
public func response(from request: Request, context: some RequestContext) -> Response {
Response(status: .ok, body: .init(string: self))
}
}
extension HTTPResponse.Status: ResponseGenerator {
public func response(from request: Request, context: some RequestContext) -> Response {
Response(status: self)
}
}
用于 DSL 的结果构建器
@resultBuilder
public enum PipelineBuilder<Context> {
public static func buildExpression<M: Middleware>(_ m: M) -> M
where M.Context == Context { m }
public static func buildPartialBlock<M0: Middleware, M1: Middleware>(
accumulated m0: M0, next m1: M1
) -> CombinedMiddleware<M0, M1> {
CombinedMiddleware(m0, m1)
}
}
// Usage
let pipeline = PipelineBuilder {
LoggingMiddleware()
AuthMiddleware()
RateLimitMiddleware()
}
静态构建器方法
public struct ServerBuilder: Sendable {
private let build: @Sendable () throws -> Server
public static func http1(config: HTTP1Config = .init()) -> ServerBuilder {
.init { HTTP1Server(config: config) }
}
public static func http2(tlsConfig: TLSConfiguration) -> ServerBuilder {
.init { HTTP2Server(tlsConfig: tlsConfig) }
}
}
// Fluent usage
let server = Application(server: .http1(config: .init(idleTimeout: .seconds(30))))
参考文件
references/api-patterns.md- 协议设计、结果构建器、构建器模式、错误处理、参数提取references/performance.md- 内联、不可复制类型、数据结构、无锁模式、状态机
评论
支持 Markdown