Enums 如果有关联的值,则枚举值测试失败?
我正在操场上测试,我不知道怎么做。对于没有关联值的普通枚举,一切正常Enums 如果有关联的值,则枚举值测试失败?,enums,swift,Enums,Swift,我正在操场上测试,我不知道怎么做。对于没有关联值的普通枚举,一切正常 enum CompassPoint { case North case South case East case West } var direction = CompassPoint.East if direction != .West { println("Go West!") } 但是,如果我的某个枚举具有关联值,则方向测试将失败,并出现以下错误:找不到成员“West” en
enum CompassPoint {
case North
case South
case East
case West
}
var direction = CompassPoint.East
if direction != .West {
println("Go West!")
}
但是,如果我的某个枚举具有关联值,则方向测试将失败,并出现以下错误:找不到成员“West”
enum CompassPoint {
case North(Int)
case South
case East
case West
}
var direction = CompassPoint.East
if direction != .West {
println("Go West!")
}
我可以做些什么来允许此测试?当枚举的原始值为
可等式时,它们会自动可等式化。在第一种情况下,假定原始值为Int
,但如果您给它另一种特定类型,如UInt32
,甚至String
,则该值可以工作
但是,一旦添加了关联值,这种与equalable
的自动一致性就不再发生,因为您可以声明:
let littleNorth = CompassPoint.North(2)
let bigNorth = CompassPoint.North(99999)
这些是平等的吗?斯威夫特怎么知道?您必须声明enum
为Equatable
,然后实现=
操作符来告诉它:
enum CompassPoint : Equatable {
case North(Int)
case South
case East
case West
}
public func ==(lhs:CompassPoint, rhs:CompassPoint) -> Bool {
switch (lhs, rhs) {
case (.North(let lhsNum), .North(let rhsNum)):
return lhsNum == rhsNum
case (.South, .South): return true
case (.East, .East): return true
case (.West, .West): return true
default: return false
}
}
现在您可以测试相等或不相等,如下所示:
let otherNorth = CompassPoint.North(2)
println(littleNorth == bigNorth) // false
println(littleNorth == otherNorth) // true
返回true的案例可以组合为单个案例:case(.South,.South),(.East,.East),(.West,.West):从Swift 4.1返回true
,因为,Swift还支持为具有关联值的枚举合成equalable
和Hashable
。