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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With