[英]Swift 4: With Codable `Generic parameter 'T' could not be inferred`
I am getting the following error: 我收到以下错误:
Generic parameter 'T' could not be inferred
on line: let data = try encoder.encode(obj)
在线:
let data = try encoder.encode(obj)
Here is the code 这是代码
import Foundation
struct User: Codable {
var firstName: String
var lastName: String
}
let u1 = User(firstName: "Ann", lastName: "A")
let u2 = User(firstName: "Ben", lastName: "B")
let u3 = User(firstName: "Charlie", lastName: "C")
let u4 = User(firstName: "David", lastName: "D")
let a = [u1, u2, u3, u4]
var ret = [[String: Any]]()
for i in 0..<a.count {
let param = [
"a" : a[i],
"b" : 45
] as [String : Any]
ret.append(param)
}
let obj = ["obj": ret]
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(obj) // This line produces an error
print(String(data: data, encoding: .utf8)!)
What am I doing wrong? 我究竟做错了什么?
That message is misleading, the real error is that obj
is of type [String: Any]
, which does not conform to Codable
because Any
does not. 该消息具有误导性,真正的错误是
obj
的类型为[String: Any]
,它不符合Codable
因为Any
没有。
When you think about it, Any
can never conform to Codable
. 当你想到它时,
Any
永远不会符合Codable
。 What will Swift use to store the JSON entity when it can be an integer, a string, or an object? 当Swift可以是整数,字符串或对象时,Swift会用什么来存储JSON实体? You should define a proper struct to hold your data.
您应该定义一个适当的结构来保存您的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.