我定义了一个枚举来表示一个"站"的 Select ;桩号由唯一的正整数定义,因此我创建了以下枚举,以允许负值代表特殊 Select :
enum StationSelector : Printable {
case Nearest
case LastShown
case List
case Specific(Int)
func toInt() -> Int {
switch self {
case .Nearest:
return -1
case .LastShown:
return -2
case .List:
return -3
case .Specific(let stationNum):
return stationNum
}
}
static func fromInt(value:Int) -> StationSelector? {
if value > 0 {
return StationSelector.Specific(value)
}
switch value {
case -1:
return StationSelector.Nearest
case -2:
return StationSelector.LastShown
case -3:
return StationSelector.List
default:
return nil
}
}
var description: String {
get {
switch self {
case .Nearest:
return "Nearest Station"
case .LastShown:
return "Last Displayed Station"
case .List:
return "Station List"
case .Specific(let stationNumber):
return "Station #\(stationNumber)"
}
}
}
}
我想用这些值作为字典中的键.声明字典会产生预期的错误,即StationSelector不符合Hashable.通过一个简单的哈希函数,很容易符合Hashable:
var hashValue: Int {
get {
return self.toInt()
}
}
然而,Hashable
要求与Equatable
一致,我似乎无法在枚举上定义equals运算符来满足编译器的要求.
func == (lhs: StationSelector, rhs: StationSelector) -> Bool {
return lhs.toInt() == rhs.toInt()
}
编译器抱怨这是一行中的两个声明,并希望在func
后加;
,这也没有意义.
有什么 idea 吗?