This question already has an answer here:
- How is Swift IF LET evaluated? 5 answers
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 userawValue
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 anil
somePlanet
is now being assign tonil
if
will evaluates the condition which issomePlanet = 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