Scrungepipes
Scrungepipes

Reputation: 37581

Defined a function as returning an optional but its returning a non optional

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

Answers (2)

Connor
Connor

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

Jiaaro
Jiaaro

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

Related Questions