簡體   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