9

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.

0

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.