子类化时出现错误 JSON (Swift)
Getting Errors when Subclassing JSON (Swift)
我对处理 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
"Errors thrown",或许可以作为解决此问题的提示。将 throws
添加到 required init
。此外,不要忘记调用 super
以使您的代码正确初始化,否则您将收到另一个错误。试试这些改变...
required init(from decoder: Decoder) throws { // add throws to eliminate errors
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)
try super.init(from: decoder) // calling super for proper intialization of code
}
附带说明:如果您没有在您的 sku 中使用任何小数点,那么您应该将类型更改为 Int
而不是 Double
。
我对处理 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
"Errors thrown",或许可以作为解决此问题的提示。将 throws
添加到 required init
。此外,不要忘记调用 super
以使您的代码正确初始化,否则您将收到另一个错误。试试这些改变...
required init(from decoder: Decoder) throws { // add throws to eliminate errors
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)
try super.init(from: decoder) // calling super for proper intialization of code
}
附带说明:如果您没有在您的 sku 中使用任何小数点,那么您应该将类型更改为 Int
而不是 Double
。