Last active
June 19, 2019 19:28
-
-
Save joshuajhomann/67c2072de0586cbff0d7d6cf463ced47 to your computer and use it in GitHub Desktop.
JSONIntitalizable
This file contains 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
protocol JSONIntitalizable { | |
init?( json: [String: Any]) | |
} | |
extension JSONIntitalizable where Self: Decodable{ | |
init?( json: [String: Any]) { | |
self = (try? JSONSerialization.data(withJSONObject: json, options: [])) | |
.flatMap{ try? JSONDecoder().decode(Self.self, from: $0) }! | |
} | |
} |
This file contains 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
protocol JSONRepresentable { | |
init?(json: [String: Any]) | |
func json() -> [String: Any]? | |
} | |
extension JSONRepresentable where Self: Codable { | |
init?(json: [String:Any]) { | |
guard let value = (try? JSONSerialization.data(withJSONObject: json, options: [])) | |
.flatMap ({ try? JSONDecoder().decode(Self.self, from: $0) }) else { | |
return nil | |
} | |
self = value | |
} | |
func json() -> [String:Any]? { | |
return (try? JSONEncoder().encode(self)) | |
.flatMap { try? JSONSerialization.jsonObject(with: $0, options: []) } as? [String: Any] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment