如何使用didSet
协议调用Codable
方法。
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 ?? "")
答案 0 :(得分:2)
您应该只使referenceToCurrentServiceAtStart -> currentService -> (Service> in memory)
成为只读的计算属性,而不是使用didSet。请注意,在命名属性时使用extendedText
代替camelCase
是Swift惯例:
snake_case
struct Sample: Codable {
let text: String
var extendedText: String {
return "***" + text + "***"
}
}
另一种方法是,如果您的目标是在初始化Codable结构时运行方法,那就是编写自己的自定义解码器:
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)
}
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")
}
}
这将打印:
确实设置了
示例文本