If I have the following enum defined:
enum CardRank {
case number(Int)
case jack
case queen
case king
case ace
}
I know I can use an if-let
to check if it's a number:
let cardRank = CardRank.number(5)
if case .number = cardRank {
// is a number
} else {
// something else
}
Instead of using an if statement, though, I want to assign the boolean result of "is this a number" to a variable.
E.g. something like this:
let isNumber = (case .number = cardRank)
However, this gives me the compiler error:
error: expected expression in list of expressions
let isNumber = (case .number = cardRank)
^
Is there a similar 1-line syntax to get this kind of assignment to work?
The closest I got was this, but it's pretty messy:
let isNumber: Bool = { if case .number = cardRank { return true } else { return false } }()
I know I can implement the Equatable protocol on my enum, and then do the following:
let isAce = cardRank == .ace
But I'm looking for a solution that doesn't require needing to conform to the Equatable protocol.
Add it as a property on the enum:
extension CardRank {
var isNumber: Bool {
switch self {
case .number: return true
default: return false
}
}
}
let isNumber = cardRank.isNumber
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With