I have cases that I need to check if an enum does not match certain case. I have been using these:
enum Enum {
case a, b(Int)
}
let a = Enum.a
if case .b = a {
// nothing
} else {
print("something")
}
switch a {
case .b: break
default: print("something")
}
They are quite clunky for what I intend to do, is there a more Swifty way to go about this?
You can leave out the associated values when testing a case already; your code didn't add anything. (The OP already used the capability in his/her example.) And your code didn't solve the original problem.
In my example, the nested Foo.Case enum is Equatable, as all simple enums are. Therefore, the == and != operators can be used on values of type Foo.Case.
The case property on Foo returns an instance of Foo.Case. Thus, when x is an instance of Foo, it follows that x.case is an instance of Foo.Case, and can be used with !=.
The confusion is because your example used == instead of !=. I assume that was a typo. Thus it appeared unrelated. And since if x.case == .a {} is no improvement over if case .a = x {}, the general usefulness was not immediately evident either.
Your suggestion was on‐topic and reasonable:
if x.case != .a {
// There is no pattern equivalent for this.
}
if x.case == y.case {
// This cannot be done just by switching either.
}