ObjectMapper-在子类中初始化一个空的初始化

问题描述 投票:0回答:1

我有一个称为“ Base”的基类,该基类实现了Mappable协议。我已经按如下所述对该类进行了子类化。

class Base: Mappable {
    var base: String?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        base <- map["base"]
    }
}

class Subclass: Base {
    var sub: String?

    required init?(map: Map) {
        super.init(map: map))
    }

    override func mapping(map: Map) {
        super.mapping(map: map)

        sub <- map["sub"]
    }
}

是否有可能在子类中创建一个空的init,以便我可以像这样创建子类的实例?

var obj = Subclass()
swift objectmapper
1个回答
0
投票

您可以在init()中添加Base,在override init()中添加SubClass

class Base: Mappable {
    var base: String?

    init() {}

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        base <- map["base"]
    }
}

class Subclass: Base {
    var sub: String?

    override init() {
        super.init()
    }

    required init?(map: Map) {
        fatalError("init(map:) has not been implemented")
    }

    override func mapping(map: Map) {
        super.mapping(map: map)

        sub <- map["sub"]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.