gpt4 book ai didi

ios - 协议(protocol)类型 'Encodable' 的值不能符合 'Encodable' ;只有结构/枚举/类类型可以符合协议(protocol)

转载 作者:行者123 更新时间:2023-12-01 18:03:34 24 4
gpt4 key购买 nike

我有以下 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
}

最佳答案

Encodable不能用作带注释的类型。它只能用作通用约束。和JSONEncoder只能编码具体类型。

功能

func doStuff<T: Encodable>(payload: [String: T]) {

是正确的,但您不能使用 [String: Encodable] 调用该函数因为一个协议(protocol)不能符合自己。这正是错误消息所说的。

主要问题是 things的真实类型是 [String:Any]Any无法编码。

你必须序列化 thingsJSONSerialization或创建一个辅助结构。

关于ios - 协议(protocol)类型 'Encodable' 的值不能符合 'Encodable' ;只有结构/枚举/类类型可以符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62252547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com