swift-library-design について
Swift のライブラリやフレームワークを設計する開発者向けのスキルです。プロトコル中心の API、コンパイル時の安全性、性能、Result Builder などの設計パターンを扱います。
主な機能
- 01プロトコル中心の API 設計
- 02コンパイル時安全性のパターン
- 03性能を意識した API の指針
- 04Result Builder と DSL のパターン
- 05ビルダーとエラー処理の資料
活用シーン
- 01再利用可能な Swift ライブラリ API の設計
- 02型安全なフレームワークの構築
- 03Result Builder による 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 向けの Result Builder
@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 対応