NOT condition in 'if case' statement
Solution 1:
This "answer" is nothing more than writing your awkward solution in a more compact manner. If you only care about the case when a value is not of a certain enum value, you could write it like this all in one line with the else
immediately following the empty then clause:
enum E {
case A, B(String), C(Int)
}
let a: E = .B("Hello")
if case .A = a {} else {
print("not an A")
}
if case .B = a {} else {
print("not a B")
}
if case .C = a {} else {
print("not a C")
}
Solution 2:
There aren't any answers yet mentioning the guard
statement, introduced by Swift 2, which is a neat addition to the tools above and, if you ask me, the cleanest solution if you can live with the requirement to return
from your function or closure within the else
-block:
guard case .B = a else {
// a does not match .B
return
}
See Apple's "The Swift Programming Language (Swift 2.2): Statements" for more info.
Solution 3:
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")
}