SwiftConformableExistential

一组 Swift 宏,旨在帮助存在类型遵循 EquatableHashableDecodableEncodableCodable 协议。

概述

在 Swift 获得对 扩展存在类型 的支持之前,它们自身无法满足泛型约束。

protocol Drinkable: Hashable {}

// Is ill-formed, because `any Drinkable` does not conform to `Hashable`,
// despite the fact that every `Drinkable` instance does.
struct Foo: Hashable {
    let drinkable: any Drinkable
}

克服此限制需要大量的样板代码。此包提供了一组宏,可以附加到您的协议,以在带注释协议的存在类型之上合成即用型属性包装器。这些包装器充当相应一致性的代理。

import SwiftConformableExistential

@HashableExistential
protocol Drinkable: Hashable {}

// `HashableDrinkable` is a `Hashable` wrapper over `any Drinkable`,
// synthesized of the attached `@HashableExistential` macro,
// allowing the compiler to now synthesize the `Hashable` implementation for `Foo`.
struct Foo: Hashable {

    @HashableDrinkable
    var drinkable: any Drinkable
}

或者,包装器也可以即时使用,特别是在不适合使用属性包装器的情况下。

struct Tap: View {

    @State private var drinkable: any Drinkable = .smallBeer
    
    var body: some View {
        ...           
        .onChange(of: HashableDrinkable(drinkable)) { _, newValue in
            prepareForPouring(newValue.wrappedValue)
        }
    }
}

欲了解更多信息,请参阅文档

安装

通过 SwiftPM。

在您的包依赖项中

.package(url: "https://github.com/stansmida/swift-conformable-existential.git", from: "0.4.0"),

以及在您的目标依赖项中

.product(name: "SwiftConformableExistential", package: "swift-conformable-existential"),

并且不要忘记在注释协议的文件中导入

import SwiftConformableExistential