繁体   English   中英

如何使用`Codable`协议调用`didSet`方法

[英]How can I call `didSet` method using `Codable` protocol

如何使用可Codable协议调用didSet方法。

    class Sample: Codable{
        var text : String? {
            didSet {
                print("didSet") // do not call
                extended_text = "***" + text! + "***"
            }
        }
        var extended_text : String?
    }

    let sample_json = "{\"text\":\"sample text\"}"
    let decoder = JSONDecoder()
    let sample = try! decoder.decode(Sample.self, from: sample_json.data(using: .utf8)!)
    print(sample.text!)
    print(sample.extended_text ?? "") 

而不是使用didSet,您应该仅使extendedText为只读的计算属性。 请注意,命名属性时,使用camelCase而不是snake_case是Swift惯例:

struct Sample: Codable {
    let text: String
    var extendedText: String {
        return "***" + text + "***"
    }
}

let sampleJson = """
{"text":"sample text"}
"""

do {
    let sample = try JSONDecoder().decode(Sample.self, from: Data(sampleJson.utf8))
    print(sample.text)            // "sample text\n"
    print(sample.extendedText)    // "***sample text***\n"
} catch {
    print(error)
}

如果您的目标是在初始化Codable结构时运行方法,则可以选择编写自己的自定义解码器:

class Sample: Codable {
    let text: String
    required init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        text = try container.decode(String.self)
        print("did set")
    }
}

let sampleJson = "{\"text\":\"sample text\"}"
let decoder = JSONDecoder()
do {
    let sample = try decoder.decode([String: Sample].self, from: Data(sampleJson.utf8))
    print(sample["text"]?.text ?? "")
} catch {
    print(error)
}

这将打印:

确实

示范文本

暂无
暂无

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

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