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!
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 tolet forSureNames = strArray?" Right?This is because
let forSureNames = strArrayis not an expression. You are parsing this statement wrong. The wordletis part of theif letstatement.You are confusing
if letstatements with C-style if statements, where after theif, there is always an expression that evaluates toBool.if letsimply does not work like that. It takes the form:where
expressionmust evaluate to an optional type. So putting()aroundlet <identifier> = <expression>makes little sense. You could put()aroundstrArraybecause that is an expression, but I don't see the point of that.