我有以下Swift代码
func doStuff<T: Encodable>(payload: [String: T]) {
let jsonData = try! JSONEncoder().encode(payload)
// Write to file
}
var things: [String: Encodable] = [
"Hello": "World!",
"answer": 42,
]
doStuff(payload: things)导致错误
Value of protocol type 'Encodable' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols怎么修?我想我需要改变things的类型,但我不知道该怎么做。
更多信息:
如果我将doStuff更改为非泛型,则该函数只会遇到相同的问题。
func doStuff(payload: [String: Encodable]) {
let jsonData = try! JSONEncoder().encode(payload) // Problem is now here
// Write to file
}发布于 2020-06-08 09:20:53
Encodable不能用作带注释的类型。它只能用作泛型约束。JSONEncoder只能对具体类型进行编码。
功能
func doStuff<T: Encodable>(payload: [String: T]) {是正确的,但是不能用[String: Encodable]调用函数,因为协议本身不符合。错误信息就是这么说的。
主要问题是,真正的things类型是[String:Any],而Any不能被编码。
您必须使用things序列化JSONSerialization或创建帮助器结构。
发布于 2020-10-21 21:03:06
可以将where关键字与Value类型结合使用,如下所示:
func doStuff<Value>(payload: Value) where Value : Encodable {
...
}发布于 2020-06-07 22:52:12
您正在尝试使T与Encodable保持一致,如果T == Encodable的话,这是不可能的。协议本身不符合规定。
相反,你可以尝试:
func doStuff<T: Hashable>(with items: [T: Encodable]) {
...
}https://stackoverflow.com/questions/62252547
复制相似问题