【问题标题】:Inheritance and constructors. Self used before super.init继承和构造函数。在 super.init 之前自用
【发布时间】:2018-12-28 12:53:34
【问题描述】:

我是 swift 继承的新手,我想了解如何以最佳方式创建构造函数。 我收到一个错误Must call a designated initializer of the superclass 'Base'

class Base{
    var id:String
    var link:String

    convenience init?(json: [String: Any]) {
        guard let id = json["id"] as? String,
            let link = json["link"] as? String else{
                print("Failed Base Class Init!")
                return nil
        }
        self.init(id: id, link: link)
    }

    init(id: String, link: String) {
        self.id = id
        self.link = link
    }
}

class Image: Base{
    func addImageToView(imageView: UIImageView){
        Alamofire.request(self.link).responseImage { response in
            if let img = response.result.value {
                imageView.image = img
            }
        }
    }
}

class Gallery:Base{
    var images:[Image] = []

    init?(json: [String: Any]){
        super.init(json: json) // Here i get <- Must call a designated initializer of the superclass 'Base'
        guard let tab = json["images"] as? [[String:Any]] else{
            print("Failed Gallery Image Init!")
            return nil
        }
        images = tab.compactMap{return Image(json: $0)}
    }
}

如何让我的类库从 json 创建一个图像表并初始化 id 和链接?

【问题讨论】:

    标签: swift class init


    【解决方案1】:

    使init?(json(也)成为指定的初始化器

    init?(json: [String: Any]) {
        guard let id = json["id"] as? String,
            let link = json["link"] as? String else{
                print("Failed Base Class Init!")
                return nil
        }
        self.id = id
        self.link = link
    }
    

    并在子类中覆盖它

    override init?(json: [String: Any]) {
      super.init(json: json) 
      ...
    

    【讨论】:

    • 感谢您完成了我所期望的工作 :)
    猜你喜欢
    • 1970-01-01
    • 2014-11-22
    • 2016-03-24
    • 2011-12-27
    • 2017-11-17
    • 2020-08-07
    • 2012-09-03
    相关资源
    最近更新 更多