【发布时间】:2019-03-24 21:56:12
【问题描述】:
我想表达一个 Swift 协议,类似于以下两个都无法编译的 sn-ps。
尝试 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' clause cannot be attached to a non-generic declaration.
这两个示例都试图表达一个协议,该协议描述的函数不是实际函数类型(A) -> B 的实例。如果有Vector2 和Vector3 类型,可以想象创建Matrix2x2、Matrix2x3 和Matrix3x3 类型并使它们符合AbstractFunction 协议。 MatrixNxM 的域是 VectorM,而 codomain 是 VectorN。方阵有一个单位矩阵,但是当域和余域不同时,单位矩阵(或真正的单位函数)的概念没有意义。
因此,我希望协议AbstractFunction 要求符合类型以提供标识,但仅限于Domain == Codomain 的情况。这可能吗?
【问题讨论】:
标签: swift swift-protocols associated-types