Mat*_*Bak 20 generics ios swift
我有以下 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)
Run Code Online (Sandbox Code Playgroud)
导致错误
Value of protocol type 'Encodable' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols
Run Code Online (Sandbox Code Playgroud)
怎么修?我想我需要更改 的类型things
,但我不知道该怎么做。
附加信息:
如果我更改doStuff
为不通用,我只会在该函数中遇到相同的问题
func doStuff(payload: [String: Encodable]) {
let jsonData = try! JSONEncoder().encode(payload) // Problem is now here
// Write to file
}
Run Code Online (Sandbox Code Playgroud)
vad*_*ian 15
Encodable
不能用作带注释的类型。它只能用作通用约束。并且JSONEncoder
只能编码具体类型。
功能
func doStuff<T: Encodable>(payload: [String: T]) {
Run Code Online (Sandbox Code Playgroud)
是正确的,但您不能调用该函数,[String: Encodable]
因为协议不能符合自身。这正是错误消息所说的。
主要问题是真正的类型things
是[String:Any]
并且Any
不能被编码。
你必须序列things
与JSONSerialization
或创建一个帮助结构。
您可以将where
关键字与Value
type 结合使用,如下所示:
func doStuff<Value>(payload: Value) where Value : Encodable {
...
}
Run Code Online (Sandbox Code Playgroud)