【发布时间】:2020-06-07 22:34:17
【问题描述】:
我有以下 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
}
【问题讨论】:
-
你的目标是什么?你想达到什么目的?您打算将字典值作为协议而不是类型做什么?
-
@matt 我最初的问题可能不够清楚。我需要将参数序列化为
doStuff。如果我将签名更改为您的建议,我将遇到与我描述的完全相同的问题,就在我调用编码函数时。