我有一个实现Swift 4的Codable
的 struct .有没有一种简单的内置方法可以将该 struct 编码到字典中?
let struct = Foo(a: 1, b: 2)
let dict = something(struct)
// now dict is ["a": 1, "b": 2]
我有一个实现Swift 4的Codable
的 struct .有没有一种简单的内置方法可以将该 struct 编码到字典中?
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
,那么你可以这样做.
let struct = Foo(a: 1, b: 2)
let dict = try struct.asDictionary()
let optionalDict = struct.dictionary
如果你想走另一条路(init(any)
),看看这个Init an object conforming to Codable with a dictionary/array