Skip to content

Instantly share code, notes, and snippets.

@KyleGoslan
Last active September 28, 2018 11:32
Show Gist options
  • Save KyleGoslan/aea9f543b08249915d7e2eab9d67b501 to your computer and use it in GitHub Desktop.
Save KyleGoslan/aea9f543b08249915d7e2eab9d67b501 to your computer and use it in GitHub Desktop.
Initilize objects from DataSnapshot that conform to the Codable protocol
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)
}
}
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