gpt4 book ai didi

ios - 在可编码类中声明空字典

转载 作者:行者123 更新时间:2023-11-28 10:33:02 24 4
gpt4 key购买 nike

我想像这样发送空字典

“visitor_attrs”: {}

我尝试在类中实现空字典。在解码器中我收到警告:

No 'decode' candidates produce the expected contextual result type 'Dictionary'

我该怎么做?

var data: String
var event: String
var visitorAttrs: Dictionary<String, Any>

init(data: String, event: String) {
self.data = data
self.event = event
self.visitorAttrs = [:]
}

private enum CodingKeys: String, CodingKey {
case data
case event
case visitorAttrs = "visitor_attrs"
}

required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.data = try container.decode(String.self, forKey: .data)
self.event = try container.decode(String.self, forKey: .event)
self.visitorAttrs = try container.decode(Dictionary<String:Any>.self, forKey: .visitorAttrs)
}

public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.data, forKey: .data)
try container.encode(self.event, forKey: .event)
try container.encode(self.visitorAttrs, forKey: .visitorAttrs)
}

最佳答案

我的假设是,因为 visitorAttrs 在您的 JSON 响应中为空,所以无法从中获取字典,因为没有字典。

你有两个选择(据我所知)

  1. 使 visitorAttrs 属性成为可选属性,这样即使您没有任何属性,它仍然能够正确解码,或者,

  2. 如果解码失败,将 visitorAttrs 的值设置为空字典

let visitorAttrs = try? container.decode(Dictionary<String:Any>.self, forKey: .visitorAttrs)
self.visitorAttrs = visitorAttrs ?? [:]

关于ios - 在可编码类中声明空字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55100233/

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