拥有通用枚举Result<T>
enum Result<T> {
case success(T)
case error
}
如何使其符合Swift版本3或更高版本中的Equatable
协议?
我尝试了以下内容:
extension Result: Equatable {
static func ==<T: Equatable>(lhs: Result<T>, rhs: Result<T>) -> Bool {
switch (lhs, rhs) {
case let (.success(lhsVal), .success(rhsVal)):
return lhsVal == rhsVal
case (.error, .error):
return true
default:
return false
}
}
}
但是,这会产生编译器错误:Type 'Result<T>' does not conform to protocol 'Equatable'
我也尝试了以下内容:
extension Result: Equatable {
static func ==(lhs: Result, rhs: Result) -> Bool {
switch (lhs, rhs) {
case let (.success(lhsVal), .success(rhsVal)):
return lhsVal == rhsVal
case (.error, .error):
return true
default:
return false
}
}
}
但是,这会产生编译器错误:Binary operator '==' cannot be applied to two 'T' operands
答案 0 :(得分:5)
将通用类型约束为Equatable
是否有帮助?
enum Result<T : Equatable> {
case success(T)
case error
}
答案 1 :(得分:1)
写此扩展而不执行:
extension Result: Equatable where T: Equatable {}
当T
符合Equatable
时,Result<T>
将自动符合Equatable
。