如果我有一个通用的结构,如...
struct Blah<T> {
let someProperty: T
}
然后,仅当
Blah
为Equatable
时,我才能扩展T
使其符合Equatable
吗?喜欢...extension Blah: Equatable where T: Equatable {
static func == (lhs: Blah, rhs: Blah) -> Bool {
return lhs.someProperty == rhs.someProperty
}
}
这可能吗?
我尝试了几种不同的编码方式,但是每种方式都给我一个略有不同的错误。
最佳答案
更新:在Swift 4.1中实现了条件一致性,
和你的代码
struct Blah<T> {
let someProperty: T
}
extension Blah: Equatable where T: Equatable {
static func == (lhs: Blah, rhs: Blah) -> Bool {
return lhs.someProperty == rhs.someProperty
}
}
可以按照Xcode 9.3中的预期进行编译和工作。
您正在寻找的是
(这又是"Generics Manifesto"的一部分)。
该提案已被Swift 4接受,但尚未实现。
从提案中:
一个突出的例子是
extension Array: Equatable where Element: Equatable {
static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool { ... }
}
使相等的元素数组相等,这是不可能的
目前。您的例子本质上是
struct SomeWrapper<Wrapped> {
let wrapped: Wrapped
}
extension SomeWrapper: Equatable where Wrapped: Equatable {
static func ==(lhs: SomeWrapper<Wrapped>, rhs: SomeWrapper<Wrapper>) -> Bool {
return lhs.wrapped == rhs.wrapped
}
}
从那个建议。