gpt4 book ai didi

ios - 为什么 Int 枚举作为字典键,产生与 Int 作为字典键不同的 json 字符串?

转载 作者:行者123 更新时间:2023-12-03 20:23:26 25 4
gpt4 key购买 nike

我尝试使用 Int 枚举转换字典

enum TypeE: Int, Codable
{
case note = 1
case tab
}

let encoder = JSONEncoder()

let dictionary0 = [TypeE.note:"VALUE0", TypeE.tab:"VALUE1"]
var data = try encoder.encode(dictionary0)
var string = String(data: data, encoding: .utf8)!
// [1,"VALUE0",2,"VALUE1"]
print(string)
生成的json字符串输出是
[1,"VALUE0",2,"VALUE1"]
对我来说看起来很奇怪。因为,生成的 json 字符串表示一个数组。

如果我测试
let encoder = JSONEncoder()

let dictionary1 = [1:"VALUE0", 2:"VALUE1"]
var data = try encoder.encode(dictionary1)
var string = String(data: data, encoding: .utf8)!
// {"1":"VALUE0","2":"VALUE1"}
print(string)
生成的json字符串输出是
{"1":"VALUE0","2":"VALUE1"}
似乎如果我使用 Int 枚举作为字典键,生成的 json 字符串将成为数组的表示?
我的代码中是否有任何错误,或者我的期望不正确?

最佳答案

Codable的源代码为这种行为提供了解释。如果 key 不是 StringInt ,结果类型是 Array :

  public func encode(to encoder: Encoder) throws {
if Key.self == String.self {
// Since the keys are already Strings, we can use them as keys directly.
...
} else if Key.self == Int.self {
// Since the keys are already Ints, we can use them as keys directly.
...
} else {
// Keys are Encodable but not Strings or Ints, so we cannot arbitrarily
// convert to keys. We can encode as an array of alternating key-value
// pairs, though.
var container = encoder.unkeyedContainer()
for (key, value) in self {
try container.encode(key)
try container.encode(value)
}
}
}

关于ios - 为什么 Int 枚举作为字典键,产生与 Int 作为字典键不同的 json 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66114149/

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