[英]Inheritance and constructors. Self used before super.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和鏈接?
使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)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.