swift - 在 Swift 中,您能否创建一个仅在特定条件满足相关类型时才需要特定功能的协议(protocol)?

标签 swift swift-protocols associated-types

我想表达一个类似于以下两个都无法编译的片段的 Swift 协议(protocol)。

尝试 1:

protocol AbstractFunction {
    associatedtype Domain
    associatedtype Codomain

    func apply(_ x: Domain) -> Codomain

    static var identity: Self where Domain == Codomain { get }
}

尝试 2:

protocol AbstractFunction {
    associatedtype Domain
    associatedtype Codomain

    func apply(_ x: Domain) -> Codomain

    static func identity() -> Self where Domain == Codomain { get }
}

第一个在 Swift 语法中甚至无效,而第二个失败 'where' 子句不能附加到非通用声明

这两个示例都试图表达一个协议(protocol),该协议(protocol)描述的函数不是实际函数类型 (A) -> B 的实例。如果有类型 Vector2Vector3,可以想象创建类型 Matrix2x2Matrix2x3Matrix3x3 并使它们符合 AbstractFunction 协议(protocol)。 MatrixNxM 的定义域是 VectorM,codomain 是 VectorN。方矩阵有一个单位矩阵,但当域和辅域不同时,单位矩阵(或真正的单位函数)的概念就没有意义了。

因此,我希望协议(protocol) AbstractFunction 要求符合类型以提供身份,但仅限于 Domain == Codomain 的情况。这可能吗?

最佳答案

您可以通过声明第二个更严格的协议(protocol)来实现它:

protocol AbstractFunction {
    associatedtype Domain
    associatedtype Codomain

    func apply(_ x: Domain) -> Codomain
}

protocol AbstractEndofunction: AbstractFunction where Codomain == Domain {
    static var identity: Self { get }
}

Int 示例 -> Int 函数:

final class IntFunction: AbstractEndofunction {
    typealias Domain = Int

    static var identity = IntFunction { $0 }

    private let function: (Int) -> Int

    init(_ function: @escaping (Int) -> Int) {
        self.function = function
    }

    func apply(_ x: Int) -> Int {
        return function(x)
    }
}

关于swift - 在 Swift 中,您能否创建一个仅在特定条件满足相关类型时才需要特定功能的协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55328952/

相关文章:

swift - 使用 associatedType 作为 Type 从泛型类继承协议(protocol)

ios - 使 Collection 符合自定义协议(protocol)

ios - 如何在两个协议(protocol)之间共享关联类型?

swift 4 : How to set top constraint when you have a navigation controller?

ios - 自定义快速相机圈触摸响应

Swift:使具有相同 "shape"的两种类型符合通用协议(protocol)

具有关联类型和影子类型删除的 Swift 协议(protocol)

从 firebase 快速加载图像

ios - 如何从停止点恢复动画?

swift - 如何检查是否符合 Swift 中关联类型的协议(protocol)?