在父类上创build一个可以被其所有子类访问的函数

我试图创build一个父类的function,可以访问它的子类。 我遇到的问题是函数的一部分,是指需要在子类中发生的init。 我收到一个错误:

传递给调用的参数不需要参数

我不完全知道如何使它的子类没有复制和粘贴到每个子类中的function。

这是父类:

class JSONObject: NSObject { 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 { let jsonInfo = JSONObject(resultsDictionary: resultsDictionary)// Here is where the error "Argument passed to call that takes no arguments" happens completion(jsonInfo) } } } } 

这是一个样本子类:

 class AirBnBObject: JSONObject { var airbnbUS: Int var airbnbLocal: Int init(airbnbUS: Int, airbnbLocal: Int){ self.airbnbUS = airbnbUS self.airbnbLocal = airbnbLocal } 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 } } 

我会转向使用一个协议,而不是一个类,这样你可以devise你的JSONObject,要求任何实现它的类也实现init(resultsDictionary:[String:Any])。 这允许你在协议扩展中写入你的updateResultsDictionary函数(这会导致任何实现类也inheritance该函数)。

协议看起来像这样:

 protocol JSONObject: class, NSObjectProtocol { init(resultsDictionary: [String:Any]) } extension JSONObject { static func updateResultsDictionary<T: JSONObject>(urlExtension: String, completion: @escaping (_ jsonObject: T?) -> 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 { let jsonInfo = T(resultsDictionary: resultsDictionary) completion(jsonInfo) } } } } 

该函数需要是通用的,以避免你所看到的错误“协议types不能被实例化”。 使用符合JSONObject的类T而不是JSONObject本身修复了错误。 (请注意,在使用T将是你的符合类,见下文)


而任何实现类将如下所示:

 class AirBnBObject: NSObject, JSONObject { var airbnbUS: Int var airbnbLocal: Int init(airbnbUS: Int, airbnbLocal: Int){ self.airbnbUS = airbnbUS self.airbnbLocal = airbnbLocal } required 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 } } 

要使用这个类的扩展function,你需要这样做:

 AirBnBObject.updateResultsDictionary(urlExtension: "") { (_ jsonObject: AirBnBObject?) -> Void in print("update results dictionary") }