Reputation: 30411
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
Upvotes: 2
Views: 372
Reputation: 2338
It's on purpose that property observers are not called in initializers. Consider the code below; the program would crash if this struct
was made an instance of. That's because the observers access other properties before they have been set. Because of this, it was chosen not to have observers run from initializers.
struct Struct {
var p1: Int { didSet { p2 = p3 * 2 } }
var p2: Int { didSet { p1 = p3 / 2 } }
var p3: Int
init(_ p1: Int, _ p2: Int, _ p3: Int) {
self.p1 = p1 // The program crashes at this point, because `p3` was not yet set.
self.p2 = p2
self.p3 = p3
}
}
To circumvent this, you can create a function that you call from both the observers and the initializer, or you can look at this.
Upvotes: 1
Reputation:
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
Upvotes: 2
Reputation: 4931
That's because the first is an instance creation - you don't set the property as the name suggests. If you need something to happen on instance creation just do it in the init method like this:
struct MyStruct {
init(myValue: Int) {
self.myValue = myValue
doSomething()
}
}
Upvotes: 1