Nếu bạn không nhớ một chút chuyển dữ liệu xung quanh bạn có thể sử dụng một cái gì đó như thế này:
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
}
}
Hoặc một varient tùy chọn
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] }
}
}
Giả sử Foo
phù hợp với Codable
hoặc thực sự Encodable
sau đó bạn có thể làm điều này.
let struct = Foo(a: 1, b: 2)
let dict = try struct.asDictionary()
let optionalDict = struct.dictionary
Nếu bạn muốn đi theo con đường khác (init(any)
), hãy xem này Init an object conforming to Codable with a dictionary/array
Nguồn
2017-09-20 18:12:09
Điều này sẽ chỉ hoạt động đối với các cấu trúc có tất cả các thuộc tính cùng loại –