简体   繁体   中英

“Protocol type ' ' cannot be instantiated” error

This is an extension of the question : creating-a-function-on-a-parent-class-that-can-be-accessible-to-all-its-children

It was suggested instead of using a class for a function a protocol would be better. After attempting the protocol approach the error "Protocol type 'JSONObject ' cannot be instantiated" happens. Any help in fixing this error is appreciated. Here is the protocol:

protocol JSONObject: class, NSObjectProtocol {

  init(resultsDictionary: [String:Any])

}

extension JSONObject {

  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)// Error haapens here

        completion(jsonInfo)

      }

    }

  }

}

Use Self like this:

static func updateResultsDictionary(urlExtension: String, completion:
    @escaping (Self?) -> Void) {


    let jsonInfo = self.init(resultsDictionary: [:])

    completion(jsonInfo)

}

Because you can't init some protocol , But you can init Type which conform to the protocol .

Self means the Type not the protocol .

And here is a tutorial about Protocol-Oriented Programming in Networking which will help you design Networking Architecture.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM