Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what do parenthesis do after lazy var definition?

I am analyzing analyzing some third party code and there is a "lazy" var statement that looks like this, and I would like to understand what the parenthesis are doing after the "computed property" curly braces:

lazy var defaults:NSUserDefaults = {
    return .standardUserDefaults()
}()

The "return .standardUserDefaults()" is returning the NSUserDefaults instance object, so why add a () after the right curly brace?

thanks

like image 456
malena Avatar asked Feb 06 '16 05:02

malena


2 Answers

It means that its a block that is executed the first time defaults is accessed. Without the () it means the defaults is a block type of variable of type () -> NSUserDefaults. When you add () it means it's just NSUserDefaults which is returned by the block executed at the time of access.

like image 135
Pradeep K Avatar answered Sep 17 '22 19:09

Pradeep K


I came up with two examples. The first example is your typical computed property. It runs every time the variable is called.

var num = 0
var myName: String {
    print(num)
    return "xxx"
}


print(myName)
// 0
// xxx
num += 1
print(myName)
// 1
// xxx

The second example is a self-executing closure. As you can see, it only runs the print(num) the first time it is called.

var num = 0
var myName: String = {
    print(num)
    return "xxx"
}()


print(myName)
// 0
// xxx
num += 1
print(myName)
// xxx

To further illustrate, I've returned the num and see if it changes in a SEC. It doesn't. That means the block only runs the first time it is called, and assigns itself the return value thereafter. For all intents and purposes, after the first call, MyNum is now 0 and no longer a block.

var num = 0
var myNum: Int = {
    print(num)
    return num
}()


print(myNum)
// 0
// 0
num += 1
print(myNum)
// 0
like image 35
Xavier Chia Avatar answered Sep 17 '22 19:09

Xavier Chia