Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Particular Closure Syntax

Tags:

swift

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?

like image 236
Barry Brunning Avatar asked Jan 27 '26 15:01

Barry Brunning


1 Answers

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
    }()
}
like image 165
Bryan Chen Avatar answered Jan 30 '26 07:01

Bryan Chen