0

In the swift book by Apple, there is an enum example. It lets you convert a raw Int to a enum rank. However when I try to remove the if statement, the code gives me

Playground execution failed: error: :30:13: error: 'Rank?' does not have a member named 'simpleDesciption'

enum Rank: Int {
    case Ace = 1
    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King

    func simpleDesciption() -> String {
        switch self {
            case .Ace:
                return "ace"
            case .Jack:
                return "jack"
            case .Queen:
                return "queen"
            case .King:
                return "king"
            default:
                return String(self.toRaw())
        }
    }
}

if let convertedRank = Rank.fromRaw(1){
    let threeDescription = convertedRank.simpleDesciption()
}

// Why does it need to be wrapped in a if statement?

let convertedRank = Rank.fromRaw(1)
let threeDescription = convertedRank.simpleDesciption()
Arian Faurtosh
  • 17,987
  • 21
  • 77
  • 115

1 Answers1

2

The if let construct allows to unwrap an optional type. The Rank.fromRaw returns the Rank? optional type, which means it could either be nil or an actual value of the type.

There are two ways to unwrap the value of an optional type in Swift, one of which is the if let construct. The body of the if let is executed if the optional type is not nil, and the variable that follows if let is bound to its value (and thus has type Rank, not Rank?).

Note that if you simply write let convertedRank = Rank.fromRaw(1) without the if, convertedRank has the type Rank? and, again, cannot be directly used as a Rank without being unwrapped.

If you are sure that the value will never be nil, you can force-unwrap it by suffixing the variable name with !:

let convertedRank = Rank.fromRaw(1)
convertedRank!.simpleDescription()

But this is not recommended style, as it will fail at runtime if the value is not defined.

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234