Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `if-case` format in boolean assignment in Swift?

Tags:

enums

swift

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.

like image 936
Senseful Avatar asked Sep 01 '17 17:09

Senseful


1 Answers

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
like image 196
Rob Napier Avatar answered Sep 19 '22 18:09

Rob Napier