使用字典/数组初始化符合Codable的对象 [英] Init an object conforming to Codable with a dictionary/array

查看:196
本文介绍了使用字典/数组初始化符合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)

如果您有兴趣选择其他方式,这可能会帮助 https://stackoverflow.com/a/46329055/1453346

If you're interested in going the other way then this might help https://stackoverflow.com/a/46329055/1453346

这篇关于使用字典/数组初始化符合Codable的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆