Reputation: 37581
In the following code why is expectingThisToBeOptional of type String and not of type String! when getOptional() is returning a String!
func getOptional() -> String!
{
var s:String! = "Hello"
return s
}
if let expectingThisToBeOptional = self.getOptional()
{
// attempting to use expectingThisToBeOptional! gives error saying type is String not String!
}
else
{
// why does execution come here when run?
}
Upvotes: 1
Views: 1181
Reputation: 64644
When you use an if let
statement, the constant that you are setting contains the unwrapped value of the optional if it has a value. self.getOptional()
return a String!
which is unwrapped into a String
and assigned to expectingThisToBeOptional
.
Upvotes: 0
Reputation: 76918
The if let
syntax unwraps the optional; the else
block is executed when the optional is nil
.
Also, optionals defined with !
(rather than ?
) are "implicity unwrapped". Which means that you don't need to use the myvar!
syntax (force unwrapping operator)
See this question for more on the difference between an Optional (e.g., String?
) and an implicitly unwrapped optional (e.g., String!
)
Upvotes: 1