Swift Property Observer with One Important Caution


One of my favorite feature in Swift language is Property Observer. As Swift is still a new language, sometimes its really hard to remember all the rules while coding. Recently while I was working on my new project, there is a class and the class have a property fontSize. User can set his own font size in the app. So when user set the size, my property observer will save the font size in User Defaults to persist the data.

 

class Properties{
    static let sharedInstance = Properties()
    private let userDefaults:UserDefaults = UserDefaults()

    var fontSize:Double = 10.0{
        didSet{
            userDefaults.setValue(fontSize, forKey: "FONT_SIZE")
            userDefaults.synchronize()
            print("Font Size Saved")
        }
    }
}

let properties = Properties.sharedInstance

I was expecting, when I create the first singleton object of properties, the didSet observer will be called. But surprisingly it is not called. I found this issue during unit test of my class file. Then I set the propertly via instance and found didSet observer called.

properties.fontSize = 20.0

Actually it is written in the apple’s documentation, but I didn’t notice that carefully.

The willSet and didSet observers of superclass properties are called when a property is set in a subclass initializer, after the superclass initializer has been called. They are not called while a class is setting its own properties, before the superclass initializer has been called.

So that means,  the observers will only be called if and only if you set the value by subclass or by externally.

mahmud ahsan

Computer programmer and hobbyist photographer from Bangladesh, lives in Malaysia. My [Github | Business | Twitter | Linkedin | Instagram | Flickr | 500px]

You may also like

LEAVE A COMMENT