Darren Findlay Darren Findlay - 7 days ago 7
Swift Question

How to express "not equal to" with a Swift switch statement with tuple pattern matching

I'm trying to use pattern matching in a switch statement with a tuple to clearly express all cases where an enum doesn't equal one specific case. Here is a shortened version of my switch statement:

switch (source, type, status) {
case (.cashVoucher, _, .awaitingValidation):
return cashVoucherAwaitingValidationMessageComponants
case (.cashVoucher, _, != .awaitingValidation):
return validatedCashVoucherMessageComponants
default:
fatalError("")
}


This doesn't compile obviously becuase of the incorrect use of the != operator, but it gives you an idea of what I'm trying to achieve.

I want the first case to match a source of
.cashVoucher
and status of
.awaitingValidation
.

I want the second case to match a source
.cashVoucher
and any status apart from
.awaitingValidation
.

There are 2 solutions I can think of so far, but they're not as readable as I would like. I could simply list all other status cases, but there are 8 in total and becomes hard to read. Alernativly, I could just use case
case (.cashVoucher, _, _):
and due to the order of the switch cases it would do what I'm trying to achieve, but my switch statement actaully has 16 cases in total and relying on the order of the switch cases make it harder for the reader to understand in my opinion.

So is there any way to express this using something similar to the
!= .awaitingValidation
I have above?

Answer

You should be able to write it as:

switch (source, type, status) {
case (.cashVoucher, _, let st) where st == .awaitingValidation:
    return cashVoucherAwaitingValidationMessageComponants
case (.cashVoucher, _, let st) where st != .awaitingValidation:
    return validatedCashVoucherMessageComponants
default:
    fatalError("")
}

So assign the third value of the tuple to a constant (here st) and use where to check for equality.