【问题标题】:Inheriting codable class raises error "required' initializer"继承可编码类引发错误“必需的初始化程序”
【发布时间】:2021-03-09 00:36:04
【问题描述】:

我继承了 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'

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

【问题讨论】:

    标签: swift inheritance codable


    【解决方案1】:

    如果您允许 Xcode 修复该问题,它会将此方法添加到子类中:

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

    【讨论】:

    • 所以我留下了这个致命错误,就像我们为 UIView 子类创建自定义初始化时所做的那样,一切正常?
    • 看看这里如何实现它:link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多