Use if syntax is allowed in switch statement

In swift, the if syntax only allows me to execute statements if the variable is of a specific type. for instance

class A {...} class B: A {...} class C: A {...} func foo(thing: A) { if let b = thing as? B { // do something }else if let c = thing as? C { // do something else } } 

Is this possible with the switch statement?

I got this far, but the variables b and c are still of type A, and not cast from B and C:

 func foo(thing: A) { switch thing { case let b where b is B: // do something case let c where c is C: // do something else default: // do something else: } } 
+5
source share
1 answer

If you want to know if it is B or C, you can just say case is B and case is C

If you want to grab and throw, say case let b as B and case let c as C

+11
source

All Articles