Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Is there a way to get didSet to work when changing a property in a class?

I have a class as property with a property observer. If I change something in that class, is there a way to trigger didSet as shown in the example:

class Foo {
    var items = [1,2,3,4,5]
    var number: Int = 0 {
        didSet {
            items += [number]

var test: Foo = Foo() {
    didSet {
        println("I want this to be printed after changing number in test")

test.number = 1 // Nothing happens
like image 786
Henny Lee Avatar asked Apr 05 '15 03:04

Henny Lee

People also ask

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.

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 the use of didSet in Swift?

In Swift, didSet and willSet methods act as property observers. willSet runs a piece of code right before a property changes. didSet runs a piece of code right after the property has changed.

What is Property Observer?

Property observers observe and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the property's current value.

1 Answers

Nothing happens because the observer is on test, which is a Foo instance. But you changed test.number, not test itself. Foo is a class, and a class is a reference type, so its instances are mutable in place.

If you want to see the log message, set test itself to a different value (e.g. a different Foo()).

Or, add the println statement to the other didSet, the one you've already got on Foo's number property.

Or, make Foo a struct instead of a class; changing a struct property does replace the struct, because a struct is a value type, not a reference type.

like image 93
matt Avatar answered Oct 21 '22 00:10