「ステーション」の選択を表す列挙型を定義しました。ステーションは一意の正の整数によって定義されるため、次の列挙型を作成して、負の値で特別な選択を表すことができるようにしました。
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)"
}
}
}
}
これらの値を辞書のキーとして使用したいと思います。Dictionary を宣言すると、StationSelector が Hashable に準拠していないという予想されるエラーが発生します。Hashable への準拠は、単純なハッシュ関数を使用して簡単に行うことができます。
var hashValue: Int {
get {
return self.toInt()
}
}
ただし、Hashable
への準拠が必要Equatable
であり、コンパイラを満たすために列挙型で equals 演算子を定義できないようです。
func == (lhs: StationSelector, rhs: StationSelector) -> Bool {
return lhs.toInt() == rhs.toInt()
}
コンパイラは、これは 1 行に 2 つの宣言があり、;
afterを入れたいと文句を言いますがfunc
、これも意味がありません。
何かご意見は?