13
15

More than 5 years have passed since last update.

[Swift]値付きのenum値同士がイコールかどうかを判定する方法

Last updated at Posted at 2015-04-16
  • 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"

ただ、毎回書くのは面倒くさいですね。

参考

13
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
15