一尘不染

如何使用Swift的Codable编码成字典?

swift

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

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

阅读 594

收藏
2020-07-07

共1个答案

一尘不染

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

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可以做到这一点。

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