继承可编码类会引发错误"required' initializer"



继承了下面的Codable类

class Vehicle: Codable {
let id: Int
let name: String

init(id: Int, name: String) {
self.id = id
self.name = name
}
}
class Car: Vehicle {
let type: String

init(id: Int, name: String, type: String) {
self.type = type
super.init(id: id, name: name)
}
}

显示错误

'required' initializer 'init(from:)' must be provided by subclass of 'Vehicle'

继承可编码类的正确方法是什么?

如果你允许Xcode修复这个问题,它会将这个方法添加到子类中:

required init(from decoder: Decoder) throws {
fatalError("init(from:) has not been implemented")
}

相关内容

最新更新