Using if let syntax in switch statement

2020-08-26 11:32发布

问题:

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:
    }
}

回答1:

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.



标签: swift