Last active
October 9, 2018 10:45
-
-
Save gotev/124394de648c7fe557831be1e30de676 to your computer and use it in GitHub Desktop.
Codable Dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension Encodable { | |
public 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] } | |
} | |
} | |
public extension Decodable { | |
public extension Decodable { | |
public static func fromDictionary<T>(_ dict: [String: Any]) throws -> T where T: Decodable { | |
let data = try JSONSerialization.data(withJSONObject: dict, options: []) | |
return try JSONDecoder().decode(T.self, from: data) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment