作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我在 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/
我是一名优秀的程序员,十分优秀!