Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch with cases with casting

Tags:

ios

swift

I want to do this with a switch:

 protocol TestProtocol {}

 class A: TestProtocol {}
 class B: TestProtocol {}

 var randomObject: TestProtocol

 if let classAObj = randomObject as? A {
 } else if let classBObj = randomObject as? B {}

I want something like this:

switch randomObject {
    case let classAObj = randomObject as? A:
         ...
    case let classBObj = randomObject as? B:
         ....
     default:
         fatalError("not implemented")
}
like image 740
Godfather Avatar asked Oct 04 '16 06:10

Godfather


1 Answers

Sure you can:

switch randomObject {
case let classAObj as A:
    // Here `classAObj` has type `A`.
    // ...
case let classBObj as B:
    // Here `classBObj` has type `B`.
    // ...
default:
    fatalError("not implemented")
}

In a pattern matching expression it is as, not as?, and = randomObject is not needed, the value to match is given right after the switch keyword.

And just for the sake of completeness: Pattern matching with case let can also be used in if-statements (or while/for-statements):

if case let classAObj as A = randomObject {

} else if case let classBObj as B = randomObject {

}

However in this case there would be no reason to do so.

like image 155
Martin R Avatar answered Oct 06 '22 00:10

Martin R