Last active
September 28, 2018 11:32
-
-
Save KyleGoslan/aea9f543b08249915d7e2eab9d67b501 to your computer and use it in GitHub Desktop.
Initilize objects from DataSnapshot that conform to the Codable protocol
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
import Firebase | |
extension DataSnapshot { | |
func toObject<T:Codable>() throws -> T { | |
var newValue = value as! [String: Any] | |
newValue["uid"] = key | |
let data = try! JSONSerialization.data(withJSONObject: newValue, options: .sortedKeys) | |
return try JSONDecoder().decode(T.self, from: data) | |
} | |
} |
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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment