跳转至

Swift 模式

此文件使用 Swift 特定内容扩展 common/patterns.md。

协议导向设计

定义小而专注的协议。使用协议扩展提供共享默认实现:

protocol Repository: Sendable {
    associatedtype Item: Identifiable & Sendable
    func find(by id: Item.ID) async throws -> Item?
    func save(_ item: Item) async throws
}

值类型

  • 数据传递对象和模型使用结构体
  • 使用带关联值的枚举来建模不同状态:
enum LoadState<T: Sendable>: Sendable {
    case idle
    case loading
    case loaded(T)
    case failed(Error)
}

执行器模式

使用执行器代替锁或调度队列来管理共享可变状态:

actor Cache<Key: Hashable & Sendable, Value: Sendable> {
    private var storage: [Key: Value] = [:]

    func get(_ key: Key) -> Value? { storage[key] }
    func set(_ key: Key, value: Value) { storage[key] = value }
}

依赖注入

通过带默认参数的协议进行注入 — 生产环境使用默认实现,测试中注入模拟对象:

struct UserService {
    private let repository: any UserRepository

    init(repository: any UserRepository = DefaultUserRepository()) {
        self.repository = repository
    }
}

参考

有关基于执行器的持久化模式,请参见技能:swift-actor-persistence。 有关基于协议的 DI 和测试,请参见技能:swift-protocol-di-testing。

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC