1

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?
}
Gruntcakes
  • 37,738
  • 44
  • 184
  • 378

2 Answers2

1

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!)

Community
  • 1
  • 1
Jiaaro
  • 74,485
  • 42
  • 169
  • 190
  • In the question code the optional isn't nil, so why is the else branch still being executed? – Gruntcakes Jun 18 '14 at 18:17
  • @Sausages the question shows code which cannot possibly be all of the code in question - the function is called with a reference to `self` for instance. I suspect in his actual use the function (which I assume is a method) has more code than we're seeing, and does return nil sometimes. Because from what we can see it would never execute the else block. – Jiaaro Jun 18 '14 at 18:20
0

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.

Connor Pearson
  • 63,902
  • 28
  • 145
  • 142