1

I am recently doing a Swift project that involves a lot of pattern matching with enums that have other enums or tuples as associated values. For example:

switch something {
    case .someCase(.someOtherCase(let foo, let bar)):
        // do something with foo and bar...
        // Then,
        someFunction(.someOtherCase(foo, bar))
    // other cases...
}

Here are some minimal declarations for the above code to compile:

enum Bar {
    case someOtherCase(Int, Int)
}

enum Foo {
    case someCase(Bar)
}

func someFunction(_ bar: Bar) {
    
}

let something = Foo.someCase(.someOtherCase(1, 1))

The thing I don't like about this, is that I have to almost repeat .someCase(.someOtherCase, foo, bar) twice - once in the pattern, and once in the function call.

I would like to do something like this:

// made up syntax that doesn't compile :(
case .someCase(let nested = .someOtherCase(let foo, let bar)):
    // do something with foo and bar...
    // then:
    someFunction(nested)

This is similar to the @ pattern in Haskell.

How can I do this?

If this were an if statement, I could do two pattern matchings:

if case .someCase(let nested) = something,
    case .someOtherCase(let foo, let bar) = nested {
    // do something with foo and bar...
    // then:
    someFunction(nested)
}

But I don't think that'd work in a switch statement, as a comma in a switch case means "or", not "and". I could obviously use another if case, but that just makes the code unnecessarily deeply nested. The entire switch case being an if statement that does another pattern matching seems really awkward too.

Sweeper
  • 213,210
  • 22
  • 193
  • 313

0 Answers0