Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this curly brace block do after a var declaration?

Tags:

swift

I'm looking at this Swift code:

var modelController: ModelController {
    if _modelController == nil {
        _modelController = ModelController()
    }
    return _modelController!
}

var _modelController: ModelController? = nil

What interests me is the first line: it's declaring a variable named modelController of type ModelController, followed by some code surrounded by curly braces, which I think is called a closure in Swift.

What does this closure do? When is it executed? What is this pattern called? I'm using Swift 3.

like image 248
Flimm Avatar asked Sep 23 '16 13:09

Flimm


1 Answers

This is called a computed property. The kind you're seeing here is a read-only computed property.

Everytime you access the property (self.modelController in this case), the closure runs, returning the value that will be used for the property.

In the example given, the code checks whether another variable _modelController is set, and sets it if not, then returns that value. This is a way of lazy loading the object when it is accessed for the first time.

like image 119
Flimm Avatar answered Oct 15 '22 14:10

Flimm