tomtom tomtom - 4 years ago 136
Swift Question

Whats the difference between these two properties?

What's the difference between these two??

var sharedContextA: NSManagedObjectContext {
return CoreDataStackManager.sharedInstantce().managedObjectContext
}


var sharedContextB = {
return CoreDataStackManager.sharedInstantce().managedObjectContext
}()


To clarify, I have seen:

var variable: Type {
code
return X
}


but I don't know the name of this or how it is different than the former:

var variable = {
code
return X
}()

Answer Source

sharedContextA is a computed property. The value to be returned is computed each time the getter of the property is called.

sharedContextB uses a closure to assign a default value to the property. The closure is executed once during initialization of the type the property belongs to, afterwards the stored value is read directly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download