Search code examples
swiftswift5

using DidSet or WillSet on decodable object


I currently have a Codable object which I am initializing using:

let decoder = JSONDecoder()
let objTest: TestOBJClass = try! decoder.decode(TestOBJClass.self, from: data)

TestOBJClass:

public class TestOBJClass: Codable {
    var name: String
    var lastname: String?
    var age: Int? {
        DidSet {
            //Do Something
        }
    }
}

The object gets initialized with no issues. However, the DidSet function on the age variable is not getting called. Are we able to use these functions when working with Decodable or Encodable objects? Thank you for your help!


Solution

  • As @Larme pointed out in comments, property observers like didSet aren't called in initializers, including the one for Codable conformance. If you want that behavior, refactor the code from your didSet into a separate named function, and then at the end of your initializer call that function.

    struct MyStruct: Codable
    {
        ...
        var isEnabled: Bool {
            didSet { didSetIsEnabled() }
        }
    
        func didSetIsEnabled() {
            // Whatever you used to do in `didSet`
        }
    
        init(from decoder: Decoder) throws
        {
            defer { didSetIsEnabled() }
            ...
        }
    }
    

    Of course, that does mean you'll need to explicitly implement Codable conformance rather than relying on the compiler to synthesize it.