1

我在玩新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]没有不可编码的原因?

4

0 回答 0