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