我想表达一个类似于以下两个都无法编译的片段的 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
的实例。如果有类型 Vector2
和 Vector3
,可以想象创建类型 Matrix2x2
、Matrix2x3
和 Matrix3x3
并使它们符合 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/