A bug in Apple's Swift documentation for forced unwrapping in statements?
My iBook in Swift Programming Language contains the following example of a function that describes forced deployment in statements if
:
let possibleNumber = "123"
let convertedNumber = possibleNumber.toInt()
if convertedNumber {
println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
println("\(possibleNumber) could not be converted to an integer")
}
// prints "123 has an integer value of 123"
But that doesn't work for me. Xcode (6.0.1) requires me to explicitly map to nil
, as in
if (convertedNumber != nil) {
println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
println("\(possibleNumber) could not be converted to an integer")
}
Is my iBook wrong?
Yes, this is wrong or, better, out of date. The behavior was changed in the 4/8/2014 release and you can see the changelog here . Relevant part:
Options are already implicitly evaluated before
true
when they have a value and false when they are not, to avoid confusion when dealing with optional valuesBool
. Instead, do an explicit check against nil with operators==
or!=
to see if it contains an optional value.
That being said, you can drop the parenthesis
if convertedNumber != nil {
...
}