我正在使用新的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]
无法编码的原因?