假设存在一个通用结构:
public struct Matrix<T> where T: FloatingPoint, T: ExpressibleByFloatLiteral {
// some methods...
}
是否可以扩展结构以符合约束T
使用where
子句的协议?例如像
extension Matrix where T: SpecificClass : SomeProtocol {
// This does not compile :(
}
假设存在一个通用结构:
public struct Matrix<T> where T: FloatingPoint, T: ExpressibleByFloatLiteral {
// some methods...
}
是否可以扩展结构以符合约束T
使用where
子句的协议?例如像
extension Matrix where T: SpecificClass : SomeProtocol {
// This does not compile :(
}
不,这样的构造是不可能的(至少在 Swift 3.1 左右)。
例如:
class SomeClass { }
protocol SomeProtocol { }
extension Matrix: SomeProtocol where T == SomeClass { }
给出一个非常清晰的错误信息:
带约束的类型扩展
Matrix
不能有继承子句。
但一切都没有丢失......正如亚历山大正确指出的那样,已经有一个针对 Swift 4 的提案!该功能将称为条件一致性 (SE-0143)。
对于所有面向协议的编程黑客来说,这是一个很好的例子:
extension Array: Equatable where Element: Equatable {
...
}
如果一个数组包含可等价的元素,则该数组也是可等价的。
更新。Swift 4 已经发布,但是这个功能还没有落地。我们可能需要等到 Swift 5 才能做到这一点......