I have a switch case statement over an enum type with associated values in Swift:
enum Foo {
case Something(let s: Any)
// …
}
I would like to use a cast in the pattern match, a bit like this:
let foo: Foo = // …
switch foo {
case .Something(let a as? SpecificType):
// …
}
In other words, I would like the case pattern to succeed only if the cast succeeds. Is that possible?
Your example basically works as is:
enum Foo {
case Something(s: Any)
}
let foo = Foo.Something(s: "Success")
switch foo {
case .Something(let a as String):
print(a)
default:
print("Fail")
}
If you replace "Success" with e.g. the number 1 it will print "Fail" instead. Is that what you want?
You can use where clause:
enum Foo {
case Something(s: Any)
}
let foo: Foo = Foo.Something(s: "test")
switch foo {
case .Something(let a) where a is String:
print("Success")
default:
print("Failed")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With