本文介绍了使用字典/数组初始化符合Codable的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的用例主要是使用字典创建对象:例如
Primarily my use case is to create an object using a dictionary: e.g.
struct Person: Codable { let name: String } let dictionary = ["name": "Bob"] let person = Person(from: dictionary)我想避免编写自定义实现并希望尽可能地高效。
I would like to avoid writing custom implementations and want to be as efficient as possible.
推荐答案目前我所拥有的最佳解决方案是此方法,但是它的开销很大
At the moment the best solution I have is this but it has the overhead of encoding/decoding.
extension Decodable { init(from: Any) throws { let data = try JSONSerialization.data(withJSONObject: from, options: .prettyPrinted) let decoder = JSONDecoder() self = try decoder.decode(Self.self, from: data) } }在问题中的示例之后,结果将是
Following from the example in the question the result would be
let person = Person(from: dictionary)如果您有兴趣选择其他方式,这可能会帮助 stackoverflow/a/46329055/1453346
If you're interested in going the other way then this might help stackoverflow/a/46329055/1453346
更多推荐
使用字典/数组初始化符合Codable的对象
发布评论