ios - "Protocol type ' ' cannot be instantiated"错误

标签 ios swift protocols

这是问题的扩展:creating-a-function-on-a-parent-class-that-can-be-accessible-to-all-its-children

有人建议使用协议(protocol)而不是为函数使用类会更好。尝试协议(protocol)方法后,发生错误“无法实例化协议(protocol)类型‘JSONObject’”。感谢您提供修复此错误的任何帮助。这是协议(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)

      }

    }

  }

}

最佳答案

像这样使用 Self:

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


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

    completion(jsonInfo)

}

因为你不能初始化一些protocol,但是你可以初始化符合protocolType

Self 是指 Type 而不是 protocol

这是一个关于 Protocol-Oriented Programming in Networking 的教程这将帮助您设计网络架构。

关于ios - "Protocol type ' ' cannot be instantiated"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646070/

相关文章:

ios - 从 iOS 应用程序获取网络类型

swift - 我如何访问警报中 Uitextfield 的文本?

ios - 在 Tableview 单元格中动态应用渐变颜色 Swift

objective-c - 如何在不使用 segue.destinationViewController 作为 setDelegate 方法的接收者的情况下设置委托(delegate)?

ios - 从intel到arm交叉编译一个库

ios - 我应该如何处理缓存设置?

ios - 使用未解析的标识符 : "UNMutableNotificationContent"

swift - Swift 中的溢出(Int64)

ios - 无法采用 UITableViewDataSource 协议(protocol) - 方法不会覆盖其父类(super class)中的任何方法

http - 我可以在 HTTP header 中使用 Unicode 字符吗?