gpt4 book ai didi

json - 如何在 Swift 中对 Codables 字典进行编码?

转载 作者:搜寻专家 更新时间:2023-11-01 06:57:19 45 4
gpt4 key购买 nike

我在 Swift 中有一个 [String: Codable] 字典,我想保存到用户默认值中,但我很难这样做。

我尝试使用

将其转换为 Data
try! JSONSerialization.data(withJSONObject: dictionary, options: .init(rawValue: 0))

但这会崩溃(“JSON 写入中的无效类型 (_SwiftValue)”)

我试过使用 JSONEncoder:

JSONEncoder().encode(dictionary)

但这不会编译(“无法推断通用参数 T”)。

当然,我可以手动将我所有的 Codable 转换为 [String: Any],然后将其写入用户默认值,但由于 Codable 的全部意义在于使解码和编码变得容易,我不太确定为什么这两个上面的解决方案是不可能的(特别是第二个)?

示例:

为了重现性,您可以在 Playground 中使用此代码:

import Foundation

struct A: Codable {}
struct B: Codable {}

let dict = [ "a": A(), "b": B() ] as [String : Codable]
let data = try JSONEncoder().encode(dict)

最佳答案

Codable 作为通用约束,Any 不可编码。使用结构而不是字典:

struct A: Codable {
let a = 0
}
struct B: Codable {
let b = "hi"
}
struct C: Codable {
let a: A
let b: B
}

let d = C(a: A(), b: B())
let data = try JSONEncoder().encode(d)

关于json - 如何在 Swift 中对 Codables 字典进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52782481/

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