如果枚举值具有关联值,则测试枚举值失败? [英] Testing for enum value fails if one has associated value?
问题描述
我正在 Playground 中对此进行测试,但我不确定如何执行此操作.使用没有关联值的普通枚举,一切都很好.
I'm testing this in the Playground and I'm not sure how to do this. With a normal enum that doesn't have associated values, everything is fine.
enum CompassPoint {
case North
case South
case East
case West
}
var direction = CompassPoint.East
if direction != .West {
println("Go West!")
}
但是,如果我的枚举之一具有关联值,则方向测试将失败并显示以下错误:找不到成员West"
However, if one of my enums has an associated value, the direction test fails with this error: could not find member 'West'
enum CompassPoint {
case North(Int)
case South
case East
case West
}
var direction = CompassPoint.East
if direction != .West {
println("Go West!")
}
我能做些什么来允许这个测试?
What can I do to allow for this test?
推荐答案
当枚举具有 Equatable
的原始值时,它们会自动Equatable
.在你的第一种情况下,原始值被假定为 Int
,但如果你给它另一个特定的类型,比如 UInt32
甚至 String代码>.
Enumerations are automatically Equatable
when they have a raw value that's Equatable
. In your first case, the raw value is assumed to be Int
, but it would work if you'd given it another specific type like UInt32
or even String
.
但是,一旦添加了关联值,就不会再发生这种与 Equatable
的自动一致性,因为您可以声明:
Once you add an associated value, however, this automatic conformance with Equatable
doesn't happen any more, since you can declare this:
let littleNorth = CompassPoint.North(2)
let bigNorth = CompassPoint.North(99999)
那些是平等的吗?斯威夫特应该怎么知道?你必须告诉它,通过将 enum
声明为 Equatable
然后实现 ==
运算符:
Are those equal? How should Swift know? You have to tell it, by declaring the enum
as Equatable
and then implementing the ==
operator:
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
}
}
现在您可以测试相等或不相等,如下所示:
Now you can test for equality or inequality, like this:
let otherNorth = CompassPoint.North(2)
println(littleNorth == bigNorth) // false
println(littleNorth == otherNorth) // true
这篇关于如果枚举值具有关联值,则测试枚举值失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!