swiftconditional-statementsoption-typeforced-unwrapping

Unwrapping Optionals (Swift Playground)


Simple question for you folks about unwrapping optionals.

I've read and seen the multiple examples of unwrapping like the following

var strArray: [String]?
strArray = ["John", "Stacy", "Stephanie" ]

if let forSureNames = strArray{
   for name in forSureNames{
      print("\(name)")
   }
} else{
    print("Failed unwrapping")
}

However, My question is for if let forSureNames = strArray{...

When typing syntax similar to C++ (and from some swift examples), adding parenthesis

if (let forSureNames = strArray){

Gives the error codes:

'()' is not convertible to 'Bool'

error: MyPlayground.playground:13:4: error: expected expression in list of expressions
if(let forSureName = strArrays){
   ^
error: MyPlayground.playground:13:4: error: expected '{' after 'if' condition
if(let forSureName = strArrays){
   ^

Can anyone help explain the difference?

Edit First time I asked a question on Stack overflow and feedback is awesome. I was trying to use a similar coding style to C++ due to my familiarity for an easy transition. However, you guys made it clear that it’s an incorrect approach. Thank you for a new and technical perspective towards unwrapping. Cheers!


Solution

  • As you know, () can be used to surround an expression and it will have no effect on the evaluation of that expression, and you are asking "why can't I do the same to let forSureNames = strArray?" Right?

    This is because let forSureNames = strArray is not an expression. You are parsing this statement wrong. The word let is part of the if let statement.

    You are confusing if let statements with C-style if statements, where after the if, there is always an expression that evaluates to Bool. if let simply does not work like that. It takes the form:

    if let <identifier> = <expression> { }
    

    where expression must evaluate to an optional type. So putting () around let <identifier> = <expression> makes little sense. You could put () around strArray because that is an expression, but I don't see the point of that.