【问题标题】:ObjectMapper - Initialize an empty init in child classObjectMapper - 在子类中初始化一个空的 init
【发布时间】:2019-10-22 08:36:38
【问题描述】:

我有一个名为“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()

【问题讨论】:

  • 为什么你不能?我觉得这个问题中缺少一些信息。
  • @JoakimDanielson 我没有错过任何东西,每当我尝试这个时,我都会收到Missing argument for parameter 'map' in call
  • 我并没有说您的代码中缺少任何内容,而是有关该问题的信息,以便我们可以完全理解它。查看已接受的答案,我认为它与Mappable 有关

标签: swift objectmapper


【解决方案1】:

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

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"]
    }
}

【讨论】:

  • 但它不允许我将对象创建为var obj = Subclass()
  • @MuhammadArifulIslam 你使用什么 ObjectMapper 版本?
  • @MuhammadArifulIslam 你别忘了把init() {} 加到Baseoverride init() { super.init() }Subclass 吗?
  • 你可以用我的代码替换你的代码。我已经测试过了,我可以将空子类声明为var subClass = SubClass(),如image中所示
  • @RomanPodymov 我之前尝试过它并没有工作,现在在清理并构建它的工作之后。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2022-07-21
  • 2015-12-04
  • 2022-06-11
  • 2014-10-24
相关资源
最近更新 更多