【发布时间】:2019-03-15 18:07:52
【问题描述】:
我对在 Swift 中处理 JSON 数据还很陌生,我正在尝试对一些产品进行子类化。我不是要编码转储,但我想给你整个画面。我有三个相同的错误:从这里抛出的错误没有得到处理它们发生在required init。提前致谢。代码如下:
import UIKit
class Product: Decodable {
var category: String = ""
var material: String = ""
init() {
}
}
class TelephoneWithCord: Product {
var sku: Double
var isNew: Bool
private enum CodingKeys: String, CodingKey {
case sku = "sku"
case isNew = "isNew"
}
required init(from decoder: Decoder) {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.sku = try container.decode(Double.self, forKey: .sku)
self.isNew = try container.decode(Bool.self, forKey: .isNew)
}
}
let json = """
{
"category" : "home",
"material" : "plastic",
"sku" : 264221,
"isNew" : true
}
""".data(using: .utf8)!
let telephoneWithCord = try! JSONDecoder().decode(TelephoneWithCord.self, from: json)
telephoneWithCord.category
telephoneWithCord.material
telephoneWithCord.sku
telephoneWithCord.isNew
【问题讨论】:
-
应该是
required init(from decoder: Decoder) throws {
标签: json swift subclassing jsondecoder