Skip to content

Instantly share code, notes, and snippets.

@gotev
Last active October 9, 2018 10:45
Show Gist options
  • Save gotev/124394de648c7fe557831be1e30de676 to your computer and use it in GitHub Desktop.
Save gotev/124394de648c7fe557831be1e30de676 to your computer and use it in GitHub Desktop.
Codable Dictionary
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