我尝试使用 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)
Run Code Online (Sandbox Code Playgroud)
生成的json字符串输出是
[1,"VALUE0",2,"VALUE1"]
Run Code Online (Sandbox Code Playgroud)
对我来说看起来很奇怪。因为,生成的 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)
Run Code Online (Sandbox Code Playgroud)
生成的json字符串输出是
{"1":"VALUE0","2":"VALUE1"}
Run Code Online (Sandbox Code Playgroud)
似乎如果我使用 Int 枚举作为字典键,生成的 json 字符串将成为数组的表示?
我的代码中是否有任何错误,或者我的期望不正确?
Codable的源代码对此行为提供了解释。如果键不是 aString或 an Int,则结果类型是 an 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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |