I have a switch statement that check a tuple. One of the part of the tuple is an enum
. How can I match multiple enum
cases inside that tuple?
I've tried several things, which all lead to compiler errors. Here's one attempt:
switch (enumValue, myArray.isEmpty)
{
case (.one, true): // Fine.
...
case ((.one, .two), false): // Error: Tuple pattern cannot match values of the non-tuple type 'MyEnum'
...
}
Is there a way to do this?
CodePudding user response:
case is expecting a Tuple (Enum, Bool)
. However, ((.one, .two), false)
is of type ((Enum, Enum), Bool)
, so what you should write is the following:
case (.one, false), (.two, false):
CodePudding user response:
You can't match multiple enum cases inside the tuple, you need to specify each enum case in a separate tuple. Alternatively, if you only care about the Bool
value being false
regardless of the enum
case, you can use case (_, false):
,
case (.one, false), (.two, false):
...
case (_, false):
...
CodePudding user response:
I think you need to repeat the whole pattern again:
switch (enumValue, myArray.isEmpty)
{
case (.one, false), (.two, false):
...
}
If you don't like this, you can try making your enum less flat - grouping similar cases together. So rather than:
enum MyEnum {
case one, two, three
}
you do:
enum OneOrTwo {
case one, two
}
enum MyEnum {
case oneOrTwo(OneOrTwo), three
}
Though you may not always find good names for these groups :(