jeudi 23 août 2018

If statement with constant as condition assigning to rawValue of enumeration [duplicate]

This question already has an answer here:

Excerpt from Swift Documentation

enum Planet: Int {

    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune

}

let positionToFind = 11

if let somePlanet = Planet(rawValue: positionToFind) {
   switch somePlanet {
   case .earth: 
       print("Mostly harmless")
   default: 
       print("Not a safe place for humans")
   }
} else {
    print("There isn't a planet at position \(positionToFind)")
}

// Prints "There isn't a planet at position 11"

Here's what I think happen when we run the code:

  • Inside the condition of the if statement it will use rawValue to try to find the case name and in this case it fails to find any because there is only 8 cases so it will return a nil
  • somePlanet is now being assign to nil
  • if will evaluates the condition which is somePlanet = nil

somePlanet = nil is not a bool

why is it possible to use it as a condition of the if statement?

Aucun commentaire:

Enregistrer un commentaire