如何使用Swift的Codable编码成字典? [英] How can I use Swift’s Codable to encode into a dictionary?

查看:548
本文介绍了如何使用Swift的Codable编码成字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现Swift 4的 Codable 的结构。是否有一种简单的内置方法将该结构编码为字典?

I have a struct that implements Swift 4’s Codable. Is there a simple built-in way to encode that struct into a dictionary?

let struct = Foo(a: 1, b: 2)
let dict = something(struct)
// now dict is ["a": 1, "b": 2]


推荐答案

如果您不介意数据移位,则可以使用以下方法:

If you don't mind a bit of shifting of data around you could use something like this:

extension Encodable {
  func asDictionary() throws -> [String: Any] {
    let data = try JSONEncoder().encode(self)
    guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
      throw NSError()
    }
    return dictionary
  }
}

或可选变体

extension Encodable {
  var dictionary: [String: Any]? {
    guard let data = try? JSONEncoder().encode(self) else { return nil }
    return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
  }
}

假设 Foo 符合 Codable 或真的 Encodable ,那么您可以执行此操作。

Assuming Foo conforms to Codable or really Encodable then you can do this.

let struct = Foo(a: 1, b: 2)
let dict = try struct.asDictionary()
let optionalDict = struct.dictionary

如果您想以其他方式使用( init(any)),看看这个使用字典/数组初始化符合Codable的对象

If you want to go the other way(init(any)), take a look at this Init an object conforming to Codable with a dictionary/array

这篇关于如何使用Swift的Codable编码成字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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