The trick is that you donβt actually check with ==, but rather use the case keyword in conjunction with one = in your if statement. This is a bit contrasting intuitive at the beginning, but like if let , you get used to it pretty quickly:
enum Normal { case one case two, three } enum NormalRaw: Int { case one = 1 case two, three } enum NormalArg { case one(Int) case two, three } let normalOne = Normal.one let normalRawOne = NormalRaw.one let normalArgOne = NormalArg.one(1) if case .one = normalOne { print("A normal one") //prints "A normal one" } if case .one = normalRawOne { print("A normal \(normalRawOne.rawValue)") //prints "A normal 1" } if case .one(let value) = normalArgOne { print("A normal \(value)") //prints "A normal 1" }
The fact is that in Swift you only get a free, free enumeration equation if your enumeration uses a raw type or if you have no associated values ββ(try it, you cannot have both at the same time). However, Swift does not know how to compare cases with related values ββ- I mean, how could this be? Let's look at this example:
Normal.one == .one //true Normal.one == .two //false NormalRaw.one == .one //true NormalRaw.one == .two //false NormalArg.one(1) == .one(1) //Well...? NormalArg.one(2) == .one(1) //Well...? NormalArg.one(1) == .two //Well...?
Perhaps this explains why this cannot work out of the box:
class Special { var name: String? var special: Special? } enum SpecialEnum { case one(Special) case two } var special1 = Special() special1.name = "Hello" var special2 = Special() special2.name = "World" special2.special = special1 SpecialEnum.one(special1) == SpecialEnum.one(special2)
So, if you want enumerations with related values, you will have to implement the Equatable protocol in your enumeration yourself:
enum NormalArg: Equatable { case one(Int) case two static func ==(lhs: NormalArg, rhs: NormalArg) -> Bool { switch (lhs, rhs) { case (let .one(a1), let .one(a2)): return a1 == a2 case (.two,.two): return true default: return false } } }