![](/img/trans.png)
[英]How can I decode partially double serialized json string using `Codable` protocol?
[英]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.