【发布时间】:2020-10-08 08:49:02
【问题描述】:
在我的自定义初始化程序中,我想从 JSON 解码字典,然后将其值分配给类中的属性。令我惊讶的是,编译器不允许我解码字典,我收到错误:
Value of protocol type 'Any' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols
如果我尝试解码 [String: Decodable] 类型的字典,错误消息会显示:
Value of protocol type 'Decodable' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols
我的初始化程序如下所示:
public let total: Int
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
...
if let dict = try container.decodeIfPresent([String: Any].self, forKey: .tracks),
let value = dict["total"] as? Int { // Error is displayed at this line
total = value
} else {
total = 0
}
...
}
当我寻找答案时,我找到了this answer,根据它上面的代码应该不会造成任何问题。
【问题讨论】:
-
“我想从 JSON 解码一个字典,然后将它的值分配给类中的属性”您实际上是在寻找
nestedContainer吗? -
"我想从 JSON 解码字典,然后将其值分配给类中的属性" 您是否真的在寻找
nestedContainer?另外“根据它,上面的代码不应该引起任何问题。”您是否像用户一样添加了扩展程序?