对于[String:Codable]

时间:2017-06-11 05:27:20

标签: swift swift4 codable

我正在使用新的Codable协议和JSONEncoder

以下方法抛出一个奇怪的异常:

  private func generateJSONData(body: [String: Codable]?) -> Data? {
    guard let body = body else {
      print("empty body for json encoding")
      return nil
    }

    let encoder = JSONEncoder()
    do {
     let data = try encoder.encode(body)
      return data
    } catch {
      print("error encoding body to json")
      return nil
    }
  }

fatal error: Dictionary<String, Decodable & Encodable> does not conform to Encodable because Decodable & Encodable does not conform to Encodable.

当我将签名更改为

时,这甚至会变得更有趣

private func generateJSONData(body: [String: Encodable]?)

fatal error: Dictionary<String, Encodable> does not conform to Encodable because Encodable does not conform to Encodable.:

有趣的是,这适用于[String: String]

是否有[String: Codable]无法编码的原因?

0 个答案:

没有答案