I’ve noticed that I often need to check if a value matches one of several enum cases. While Swift is generally very expressive, this specific pattern feels a bit repetitive. I’m curious if there has ever been a discussion about making this more concise.
In a perfect world, I’d love to be able to write something like this:
if userStatus == .active || .pending {
// Do something
}
Currently, we have to repeat the variable name (userStatus == .active || userStatus == .pending), which can make if statements quite long as the variable names or the number of cases grow, and less ergonomic I guess.
I’m curious if this type of comparison has been considered before.
- Is there a fundamental reason why
||couldn't be used this way (e.g., how the compiler reads logic)? - Are there plans for "pattern matching" improvements that might cover this?
I know the syntax above isn't possible right now, so I’ve been using two alternatives:
- This works, but feels a bit "heavy" because it requires creating an array just to do a check:
if [.active, .pending].contains(userStatus) { ... }
- A simple helper to
Equatabletypes:
extension Equatable {
func isAny(of cases: Self...) -> Bool {
return cases.contains(self)
}
}
// Usage
if userStatus.isAny(of: .active, .pending) { ... }
I personally feel the extension method reads very well, but I’d love to hear the community’s thoughts on whether a native language change (like my first example) would be a nice addition to Swift.