继承和构造函数。在super.init之前自用

时间:2018-12-28 12:53:34

标签: swift class init

我是继承的新手,我想了解如何以最佳方式创建构造函数。 我收到错误消息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和链接?

1 个答案:

答案 0 :(得分:0)

使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) 
  ...