Are lazy vars in Swift calculated more than once?

Are lazy vars in Swift more than once? I got the impression that they replaced:

if (instanceVariable) { return instanceVariable; } // set up variable that has not been initialized 

The paradigm from Objective-C (lazy instance).

Is that what they do? As a rule, only once at the first request of the application it requests a variable, and then just returns what was calculated?

Or does it receive a call every time, as a normal computed property?

The reason I'm asking is because I basically want Swift to compute a property that can access other instance variables. Let's say I have a variable called "fullName", and it just combines firstName and lastName . How do I do this in Swift? It seems that lazy vars are the only way to go, as in normal computable vars (not lazy), I cannot access other instance variables.

So basically:

Are lazy vars in Swift called more than once? If so, how do I create a computed variable that can access instance variables? If not, if I want the variable to be computed once for performance reasons, how do I do this?

+23
lazy-initialization swift computed-properties
Oct. 19 '14 at 20:02
source share
3 answers

lazy var evaluated only once, upon first use. After that, they are like an ordinary variable.

This is easy to check on the playground:

 class LazyExample { var firstName = "John" var lastName = "Smith" lazy var lazyFullName : String = { [unowned self] in return "\(self.firstName) \(self.lastName)" }() } let lazyInstance = LazyExample() println(lazyInstance.lazyFullName) // John Smith lazyInstance.firstName = "Jane" println(lazyInstance.lazyFullName) // John Smith lazyInstance.lazyFullName = "???" println(lazyInstance.lazyFullName) // ??? 

If you need to recalculate it later, use the computed property (with a support variable if it's expensive) - just like you did in Objective-C.

+23
Oct. 19 '14 at 20:23
source share

No, lazy properties are initialized only once. If you set the new value or reset to nil (for additional properties), the lazy initializer will fail again.

I think that you need a computable property - it is not supported by the stored property, so it does not participate in initialization, and therefore you can refer to other properties of the instance.

Why are you saying that "normal computable vars (not lazy) I cannot access other instance variables"?

+6
Oct 19 '14 at 20:09
source share

All other answers are correct, I just wanted to add that Apple warns about lazy variables and concurrency:

If a property marked with the lazy modifier is available to several threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once.

0
Jan 23 '19 at 17:44
source share



All Articles