Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: What do brackets around an if condition change?

Tags:

xcode

swift

I try to get to grips with Swift and how to best separate nil and valid objects from optionals.

I have this code:

var my AwesomeDict = [:]()
...
... (myAwesomeDict gets populated)
...
let myOptionalObject:objectClass? = myAwesomeDict[key]
if let myUnwrappedObject = myOptionalObject {
    ...
} else {
    println("Sorry, object is nil")
}

When I put brackets around the if clause (I feel it improves readability), XCode will flag the line with a compiler error:

Pattern variable binding cannot appear in an expression

What is different about

if (let myUnwrappedObject = myOptionalObject) {

from

if let myUnwrappedObject = myOptionalObject {

? Sadly, the documentation makes no mention of the effect of braces around if conditions. It seems I need to use the bracket-free version, but would like to become more enlightened about the reason.

like image 949
Peter Kämpf Avatar asked Dec 20 '22 06:12

Peter Kämpf


1 Answers

Well here, if let is a pattern itself. So if you put a bracket between the if and let, you break the pattern.

If you do that, Swift thinks that you want to check the let itself.

So simply said: If you use if let don't use brackets, because it breaks the if let pattern.

like image 147
Christian Avatar answered Dec 24 '22 00:12

Christian