Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift can lazy and didSet set together

Tags:

I have a property

public lazy var points: [(CGFloat,CGFloat,CGFloat)] = {         var pointsT = [(CGFloat,CGFloat,CGFloat)]()         let height = 100.0         for _ in 1...10 {             pointsT.append((someValue,someValue,100.0))         }         return pointsT     }() 

And i want to add a didSet method, is it possible?

like image 733
William Hu Avatar asked Dec 23 '15 01:12

William Hu


People also ask

Can we use lazy with let in Swift?

You can't make it lazy let because lazy properties must always be variables. Because the actual value is created by evaluation, you need to declare its data type up front. In the case of the code above, that means declaring the property as Int .

What is difference between willSet and didSet in Swift?

Observer— willSet and didSetwillSet is called before the data is actually changed and it has a default constant newValue which shows the value that is going to be set. didSet is called right after the data is stored and it has a default constant oldValue which shows the previous value that is overwritten.

What is difference between didSet and willSet?

willSet is called just before the value is stored. didSet is called immediately after the new value is stored.

Is didSet called on initialization?

One thing to note is that willSet and didSet will never get called on setting the initial value of the property. It will only get called whenever you set the property by assigning a new value to it. It will always get called even if you assign the same value to it multiple times.


1 Answers

Short answer: no.

Try out this simple example in some class or method of yours:

lazy var myLazyVar: Int = {     return 1 } () {     willSet {         print("About to set lazy var!")     } } 

This gives you the following compile time error:

Lazy properties may not have observers.


With regard to the let statement in the other answer: lazy variable are not necessary just "let constants with delayed initialisation". Consider the following example:

struct MyStruct {     var myInt = 1      mutating func increaseMyInt() {         myInt += 1     }      lazy var myLazyVar: Int = {         return self.myInt     } () }  var a = MyStruct() print(a.myLazyVar) // 1 a.increaseMyInt() print(a.myLazyVar) // 1: "initialiser" only called once, OK a.myLazyVar += 1 print(a.myLazyVar) // 2: however we can still mutate the value                    //    directly if we so wishes 
like image 192
dfrib Avatar answered Sep 20 '22 11:09

dfrib