I have an enum:
enum E {
case A, B, C(Int)
}
let a: E = .A
Here\'s how I would check if a
equals .B
You are using single = sign which is an assignment operator. You have to use double == which is a comparison one and don't use case .A, use E.A is the right way to do that:
if E.A == a {
// works fine
print("1111")
}
if E.B != a {
// works fine
print("2222")
}
if E.B == a {
// works fine
print("3333")
}
Extended:
To make it works with associated values you have to implement Equatable protocol, example:
extension E: Equatable {}
func ==(lhs: E, rhs: E) -> Bool {
switch (lhs, rhs) {
case (let .C(x1), let .C(x2)):
return x1 == x2
case (.A, .A):
return true
default:
return false
}
}
Of course you have to handle all of the possibilities but I think you have an idea.
Extended:
I don't get your comment but this works for me fine:
enum E {
case A, B, C(Int)
}
extension E: Equatable {}
func ==(lhs: E, rhs: E) -> Bool {
switch (lhs, rhs) {
case (let .C(x1), let .C(x2)):
return x1 == x2
case (.A, .A):
return true
case (.B, .B):
return true
default:
return false
}
}
let a: E = .A
let b: E = .B
let c: E = .C(11)
if E.A == a {
// works fine
print("aaa true")
}
if E.A != a {
// works fine
print("aaa false")
}
if E.B == b {
// works fine
print("bbb true")
}
if E.B == b {
// works fine
print("bbb false")
}
if E.C(11) == c {
// works fine
print("ccc true")
}
if E.C(11) != c {
// works fine
print("1 ccc false")
}
if E.C(22) != c {
// works fine
print("2 ccc false")
}