9

In swift the if let syntax allows me to only execute statements if a variable is of a certain type. For example

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 it possible to achieve this with a switch statement?

I have got this far, but the variables b and c are still of type A, not cast to 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:
    }
}
2
  • 4
    if let b = thing as B Actually, that is not legal. Commented Jun 4, 2015 at 16:26
  • 2
    The right way to do it is if let b = thing as? B. Commented Jun 4, 2015 at 16:27

1 Answer 1

19

If all you want to know is whether it's a B or a C, you can just say case is B and case is C.

If you want to capture and cast down, then say case let b as B and case let c as C.

Sign up to request clarification or add additional context in comments.

2 Comments

And for a good list of switch case patterns and usages, see my book: apeth.com/swiftBook/ch05.html#_switch_statement
Is it possible to access nested properties this way? As: case let c = c as C, let m = c.item as? videoItem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.