Since the didSet method does not get called when the instance variable is set in initialization, it is common for developers to create helper methods that get called both in init method and in the didSet code block.
For example, consider this trivial example
class Example {
var images: [UIImage] {
didSet {
imageViews = images.map({ UIImageView(image: $0 )})
}
}
var imageViews: [UIImageViews]
init(images: [UIImage]) {
self.images = images
self.imageViews = images.map({ UIImageView(image: $0 )})
}
}
The generation of the imageViews array is duplicated in both the init and didSet methods. We could wrap this one line in a function call to ensure that any change to the logic gets propagated to both both places, but it would be so much simpler and more explicit if we could use a keyword to indicate that when we set self.images in the init method, we want it to trigger the didSet method as well.
I'm open to suggestions on what that keyword/syntax would look like.
I disagree that such a keyword would be more explicit. I think you're saying you want the keyword to go on the property observer. That would mean, reading init, you don't know which side effects might run or not without looking at the properties.
Possibly some shorthand that could be used insideinit would be okay, though.
Actually, I was thinking the keyword would be inside of init. So that reading it, it's easy to see that the line means "Set this initial value and call the setter". I realize that using lazy sort of solves the problem, but I take issue with the need for an additional method (in the above example, _recreateImageViews()).