- Xcode6.3 + Swift 1.2 + Playground
値付きでなければ何も気にせずとも判定可能
import UIKit
enum Fruits {
case Apple
case Orange
}
let a = Fruits.Apple
let b = Fruits.Orange
println(a == b) // "false"
println(a == .Apple) // "true"
値付きだとコンパイルエラーとなる
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let a = ServerResponse.Result("6:00 am", "8:09 pm")
let b = ServerResponse.Error("Out of cheese.")
println(a == b)
エラー
error: binary operator '==' cannot be applied to two ServerResponse operands
println(a == b)
^
解決方法(一例)
==演算子を書けばOK。
import UIKit
enum ServerResponse: Equatable {
case Result(String, String)
case Error(String)
}
func ==(a: ServerResponse, b: ServerResponse) -> Bool {
switch (a, b) {
case let (.Result(a0, a1), .Result(b0, b1)):
return a0 == b0 && a1 == b1
case let (.Error(a0), .Error(b0)):
return a0 == b0
default:
return false
}
}
let a = ServerResponse.Result("6:00 am", "8:09 pm")
let b = ServerResponse.Error("Out of cheese.")
println(a == b) // "false"
println(a == .Result("6:00 am", "hoge")) // "false"
println(a == .Result("6:00 am", "8:09 pm")) // "true"
ただ、毎回書くのは面倒くさいですね。