我在使用枚举时遇到了一个问题,但我无法理解它。
这是一个枚举类型的声明:
enum SomeType {
case un
case deux
case trois
}
接下来我想用一个if
语句匹配枚举类型中的单个值:
var testValue: SomeType = .trois
if testValue == .trois {
// Do something
}
一切都好!
现在我想仅将关联值添加到第一个成员值中:
enum SomeType {
case un(Int)
case deux
case trois
}
var testValue: SomeType = .trois
if testValue == .trois {
// Do something
}
在if
语句中出现错误:无法找到成员'trois'
这是否意味着只能使用switch
语句匹配枚举?
说明
我想实现的是:"testValue是否是'trois'成员值,不考虑关联值"。换句话说,如何仅基于成员值匹配枚举。
以下是实现Airspeed Velocity答案的解决方案:
// Test equality only on member value
func == (lhs:SomeType, rhs:SomeType) -> Bool {
switch (lhs, rhs) {
case (.un(let lhsNum), .un(let rhsNum)):return true
case (.deux, .deux): return true
case (.trois, .trois): return true
default: return false
}
}
// Test equality on member value AND associated value
func === (lhs:SomeType, rhs:SomeType) -> Bool {
switch (lhs, rhs) {
case (.un(let lhsNum), .un(let rhsNum)) where lhsNum == rhsNum: return true
case (.deux, .deux): return true
case (.trois, .trois): return true
default: return false
}
}
var testValue = SomeType.un(3)
// Tests
if testValue == .un(1) {
println("Same member value")
}
if testValue === .un(3) {
println("Same member value AND same associated contents")
}
SomeType.un
相等?如果是这样,只需在定义==
时从 switch 中删除 where 子句(即对.un
做与.deux
和.trois
相同的处理)。但是你仍然需要自己定义==
,因为 Swift 需要知道这是你想要的行为。 - Airspeed Velocity===
来包括关联值。 - Dominique Vial===
,因为它在Swift中已经用于其他用途。 - Pop Flamingo