프로그래밍/iOS,macOS
Codable for Dictionary
chance
2020. 6. 10. 15:27
extension Encodable {
func getValue() throws -> [String:Any] {
let data = try JSONEncoder().encode(self)
if let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any] {
return dictionary
}
throw NSError()
}
}
extension Decodable {
func setValue(from: [String:Any] ) throws {
let data = try JSONSerialization.data(withJSONObject: from, options: .prettyPrinted)
let decoder = JSONDecoder()
self = try decoder.decode(Self.self, from: data)
}
}