2

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!

paul590
  • 1,385
  • 1
  • 22
  • 43
  • 2
    `didSet`isn't called on `init` methods: https://stackoverflow.com/questions/25230780/is-it-possible-to-allow-didset-to-be-called-during-initialization-in-swift – Larme Mar 31 '21 at 19:02
  • Thank you! this helped me a ton! – paul590 Mar 31 '21 at 19:54

1 Answers1

2

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.

Chip Jarred
  • 2,600
  • 7
  • 12