swiftreswift

Swift typecasting/pattern-match condition this or that


My use case involves a switch statement and trying to build a case that depends on multiple typecasts. This will really help me introduce some composable/clean/less code. The generic multiple conditions won't work as I'm using let with the casting and it cant be mutated. Also, fallthrough produces a similar error.

case let foo as SomeStruct,
     let foo as SomeOtherStruct:
        // do whatever

Error: Pattern variable bound to type

case let foo as SomeStruct:
     fallthrough
case let foo as SomeOtherStruct:
     // do whatever

'fallthrough' cannot transfer control to a case label that declares variables

Those errors both make sense. Basically, Im asking if there is any way to do a typecasting/pattern-match of let foo as SomeStruct || SomeOtherStruct

Edit: for more context, Im doing reducer composition with ReSwift


Solution

  • And what about this?

    struct S1 {
        var a : String
    }
    struct S2 {
        var a : Int
    }
    let x = S1(a: "Test")
    switch x {
        case let y where (y is S1) || (y is S2): print("S1 or S2")
        default: break
    }