简体   繁体   English

在可解码 object 上使用 DidSet 或 WillSet

[英]using DidSet or WillSet on decodable object

I currently have a Codable object which I am initializing using:我目前有一个 Codable object,我正在使用它进行初始化:

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. object 初始化没有问题。 However, the DidSet function on the age variable is not getting called.但是,年龄变量上的 DidSet function 没有被调用。 Are we able to use these functions when working with Decodable or Encodable objects?在使用 Decodable 或 Encodable 对象时,我们是否能够使用这些函数? Thank you for your help!谢谢您的帮助!

As @Larme pointed out in comments, property observers like didSet aren't called in initializers, including the one for Codable conformance.正如@Larme 在评论中指出的那样,像didSet这样的属性观察器不会在初始化程序中被调用,包括Codable一致性。 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.如果您想要这种行为,请将didSet中的代码重构为单独的名为 function 的代码,然后在初始化程序结束时调用 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.当然,这确实意味着您需要显式地实现Codable一致性,而不是依赖编译器来合成它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM