使用字典/数组初始化符合Codable的对象

编程入门 行业动态 更新时间:2024-10-24 18:19:31
本文介绍了使用字典/数组初始化符合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的对象

本文发布于:2023-11-26 03:12:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632407.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   初始化   字典   对象   Codable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!