swiftstructcomputed-propertiesdidsetproperty-observer

Struct not calling property observers on new object


In this code, I would like to have the property observers called when the new object is created. How do I achieve this?

Here is what I have so far:

struct MyStruct {
    var myValue: Int {
        willSet {
            print("willSet")
        }
        didSet {
            print("didSet")
        }
    }
}

var abc = MyStruct(myValue: 3) // Does not use property observers
abc.myValue = 5 // Calls property observers

Solution

  • You can construct a custom initializer as follows.

    struct MyStruct {
        var myValue: Int {
            willSet {
                print("willSet")
            }
            didSet {
                print("didSet")
            }
        }
    
        init(value: Int) {
            myValue = value
            // print something here
        }
    }
    
    var abc = MyStruct(value: 3) 
    abc.myValue = 5