Hi all,
I’ve noticed a few common patterns recently in code that makes use of ‘if case’ statements:
if case .someEnumCase(_, someMatchingValue) = x {
return true
}
return false
if case .someEnumCase(_, someMatchingValue) = x {} else {
// do something only in the negative case
}
if case .someEnumCase(_, someMatchingValue) = x {
dict[someKey] = true
} else {
dict[someKey] = false
}
All three examples seem unnecessarily clunky due to the current restrictions on the pattern matching syntax. I’d like to pitch a proposed syntax for ‘case expressions’ that would allow us to rewrite the three examples above as:
return case .someEnumCase(_, someMatchingValue) = x
if !(case .someEnumCase(_, someMatchingValue) = x) {
//do something only in the negative case
}
dict[someKey] = case .someEnumCase(_, someMatchingValue) = x
While this would make it easier to compare enum cases without associated values, I think the feature would still be quite useful even if we adopt one of the solutions to that problem discussed here. I took a look at a ~100k LOC codebase and found a few dozen instances of the patterns above where either some associated values were being matched while others were ignored, or a custom ~= implementation was being used. To give a more realistic example which goes beyond a simple case test:
enum PaymentMethod {
case cash
case check(number: UInt)
case creditCard(number: String, cvv: String, expirationDate: Date)
var isVisa: Bool {
//Assume there’s an appropriate ~= implementation for Regex and String
return case .creditCard(number: Regex(“^4[0-9]{12}(?:[0-9]{3})?$”), cvv: _, expirationDate: _) = self
}
var isLowNumberedCheck: Bool {
return case .check(number: 0…999) = self
}
}
The syntax is intended to be easily discoverable for users who are already used to pattern matching elsewhere in the language, though it is a little more heavyweight than just introducing a new binary operator, and would add some complexity to the grammar. I’d appreciate any and all feedback/suggestions as to whether people think this might be a worthwhile addition before fleshing out this pitch some more. Thanks!