Barry Brunning
Barry Brunning

Reputation: 33

Swift Particular Closure Syntax

In this application there is the statement:

var instanceCount = { globalHappinessInstanceCount++ }()  

In trying to understand the above statement I have found that, as far as I've tested, the statement below achieves the same result:

var instanceCount = globalHappinessInstanceCount++  

Q1. What's the first statement achieving that the second doesn't?

Q2. Are the () braces following the closure expression signifying an empty tuple, initialiser syntax, ... or what? I.e how should one read the first statement?

Upvotes: 3

Views: 81

Answers (1)

Bryan Chen
Bryan Chen

Reputation: 46608

Q1. What's the first statement achieving that the second doesn't?

AFAIK it just creates an unnecessary closure which doesn't add any value...

Q2. Are the () braces following the closure expression signifying an empty tuple, initialiser syntax, ... or what? I.e how should one read the first statement?

It is method call. Just like

let foo = { globalHappinessInstanceCount++ }
foo()

Update:

I just read the code in your link, in the context of class scope, it is different.

class HappinessViewController
{
    var instanceCount = { globalHappinessInstanceCount++ }()
}

defines a property instanceCount: Int that get assigned value of globalHappinessInstanceCount++

It is not that much different than var instanceCount = globalHappinessInstanceCount++

However in Swift 3, ++ operator will be removed, which you may want to change it to globalHappinessInstanceCount += 1. But the issue is the result type of += operator is Void instead Int. So you have to write it like

class HappinessViewController
{
    var instanceCount: Int = {
        let instanceCount = globalInstanceCount
        globalInstanceCount += 1
        return instanceCount
    }()
}

Upvotes: 1

Related Questions