Reputation: 2513
Please have a look at the switch statement below. I am looking for a more swifty way to perform the test; something like:
case let .b(other) where .x = other // This does not compile
Is it possible?
enum MyEnum {
case a
case b(MyOtherEnum)
}
enum MyOtherEnum {
case x
case y
}
func check(value: MyEnum) {
switch value {
case let .b(other):
if case .x = other {
print("Got it!")
}
default:
break
}
}
Upvotes: 2
Views: 395
Reputation: 539685
If you are only interested in the case MyEnum.b(.x)
and no other
cases then you can also use if
with a case
pattern:
func check(value: MyEnum) {
if case .b(.x) = value {
print("Got it!")
}
}
Upvotes: 2
Reputation: 23701
func check(value: MyEnum) {
switch value {
case .b(.x):
print("Got it!")
case .b(_):
print("Not it!")
default:
break
}
}
let myVar = MyEnum.b(.x)
check(value: myVar)
// prints "Got it!"
Upvotes: 1
Reputation: 9777
You need to use ==
not =
:
case let .b(other) where .x == other
This works fine for me:
func check(value: MyEnum) {
switch value {
case let .b(other) where other == .x:
print("bx")
case let .b(other) where other == .y:
print("by")
default:
break
}
}
check(value: MyEnum.b(.x)) // prints "bx"
check(value: MyEnum.b(.y)) // prints "by"
Upvotes: 1