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?
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 .
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.
willSet is called just before the value is stored. didSet is called immediately after the new value is stored.
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.
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
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