我想創建一個基類來初始化自定義JSON對象。我這樣做的原因是,我不必一遍又一遍地爲每個類複製和粘貼相同的函數(updateResultsDictionary)。我現在有一個問題與超級INIT做,我不斷收到錯誤:爲自定義JSON對象創建基類
Cannot convert value of type '[String : Any].Type' (aka 'Dictionary.Type') to expected argument type '[String : Any]'
,如果我沒有正確創建的基類和子類此錯誤甚至可能沒有關係。這是基類:
class JSONObject : NSObject {
init(resultsDictionary:[String: Any]){}
//Function used for all child classes to update object values
static func updateResultsDictionary(urlExtension: String, completion:
@escaping (JSONObject?) -> Void) {
let nm = NetworkManager.sharedManager
_ = nm.getJSONData(urlExtension: urlExtension) {data in
guard let jsonDictionary = nm.parseJSONFromData(data), let
resultDictionaries = jsonDictionary["result"] as?
[[String : Any]] else {
completion(nil)
return
}
for resultsDictionary in resultDictionaries {// enumerate through dictionary
let jsonInfo = JSONObject(resultsDictionary: resultsDictionary)
completion(jsonInfo)
}
}
}
}
這是一個示例子類:
class AirBnBObject: JSONObject {
var airbnbUS: Int
var airbnbLocal: Int
init(airbnbUS: Int, airbnbLocal: Int){
super.init(resultsDictionary:[String: Any]())
self.airbnbUS = airbnbUS
self.airbnbLocal = airbnbLocal
}
override init(resultsDictionary:[String: Any]){
guard let cost = resultsDictionary["cost"] as? [String: Any],
let airbnb = cost["airbnb_median"] as? [String : Any],
let usd = airbnb["USD"] as? Int,
let chf = airbnb["CHF"] as? Int
else {
airbnbUS = 0
airbnbLocal = 0
return
}
airbnbUS = usd
airbnbLocal = chf
}
}
這是編寫JSON對象所以它可能是不正確的一種新的方式。
我只是想你的方法,現在它返回了幾個不同的錯誤:屬性「self.airbnbUS」在super.init調用沒有初始化,Super.init不叫在從初始化程序返回之前的所有路徑上 – SwiftyJD
您是否閱讀過有關初始化的Apple Swift手冊中的章節?您需要確保始終調用超類初始化程序,並且超類或初始化程序的子類初始化所有屬性。 – Paulw11
我以爲這就是我正在做的與super.init(resultsDictionary:[String:Any]()) – SwiftyJD