Compound switch cases: may we have a single common value binding for compound enum cases that have the same type of associated value? Compound switch cases: may we have a single common value binding for compound enum cases that have the same type of associated value? swift swift

Compound switch cases: may we have a single common value binding for compound enum cases that have the same type of associated value?


No, this is not possible; in the value binding examples above, x must be bound in every pattern, and this must hold separately for every pattern in the compound cases.

Quoting the Language Guide - Control Flow [emphasis mine]

Compound cases can also include value bindings. All of the patterns of a compound case have to include the same set of value bindings, and each binding has to get a value of the same type from all of the patterns in the compound case. This ensures that, no matter which part of the compound case matched, the code in the body of the case can always access a value for the bindings and that the value always has the same type.

I we try to omit the binding in one of the patterns in the compound example above, we are given quite an self-explanatory error message on the subject:

func foo(_ foo: Foo) -> Int {    switch foo {        case .bar(_), .baz(let x), .bax(let x): return x         case .fox: return 0    }}
error: 'x' must be bound in every pattern

This holds even if we don't use x in the body that follows

func foo(_ foo: Foo) -> Int {    switch foo {        case .bar(_), .baz(let x), .bax(let x): return 0         case .fox: return 0    }} // same error