我有一个实现Swift 4的结构Codable。是否有一种简单的内置方法将该结构编码为字典?
Codable
let struct = Foo(a: 1, b: 2) let dict = something(struct) // now dict is ["a": 1, "b": 2]
如果您不介意数据移位,可以使用以下方法:
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可以做到这一点。
Foo
Encodable
let struct = Foo(a: 1, b: 2) let dict = try struct.asDictionary() let optionalDict = struct.dictionary