Reputation: 4589
accodring to apple documentation the following code checks if convertedNumber has been initialized, and if so, it executes the if block.
let convertedNumber: Int?
if convertedNumber {
//do stuff
}
I'm interested in what's happening behind the scenes. Is this some sort of shorthand notation, because the condition in if statement must evaluate to boolean true or false. how is the fact that convertedNumebr contains a value transformed into true or false?
I was thinking that this is a shorthand notation for:
if convertedNumber!=nil {
//do stuff
}
correct me if I'm wrong.
Upvotes: 2
Views: 179
Reputation: 539685
The "shorthand test" for optionals
if someOptional {
//do stuff
}
existed only in early version of Swift. From the Xcode 6 beta 5 release notes:
Optionals no longer conform to the BooleanType (formerly LogicValue) protocol, so they may no longer be used in place of boolean expressions (they must be explicitly compared with v != nil). This resolves confusion around Bool? and related types, makes code more explicit about what test is expected, and is more consistent with the rest of the language.
So with current Xcode versions, you have to test with
if someOptional != nil {
//do stuff
}
or, of course, with optional binding.
In addition, struct Optional
conforms to the NilLiteralConvertible
protocol, so that (in this context) nil
is identical to
Optional<T>.None
with the matching type T
.
Upvotes: 3