Skip to content

Instantly share code, notes, and snippets.

@ts95
Created June 23, 2017 22:49
Show Gist options
  • Save ts95/3698006b7ea5c98736de426ef3bbfcb3 to your computer and use it in GitHub Desktop.
Save ts95/3698006b7ea5c98736de426ef3bbfcb3 to your computer and use it in GitHub Desktop.
An example of a book model that implements the Model protocol
import Foundation
import FirebaseDatabase
struct Book {
var id: String?
var isbn: String
var title: String
var authors: String
var year: String
var country: String
var createdAt: Date
}
// MARK: - Model
extension Book: Model {
var serialized: [String : Any] {
return [
"isbn": isbn,
"title": title,
"authors": authors,
"year": year,
"country": country,
"createdAt": createdAt.timeIntervalSince1970,
]
}
init?(snapshot: FIRDataSnapshot) {
guard
let child = snapshot.value as? [String : Any],
let isbn = child["isbn"] as? String,
let title = child["title"] as? String,
let authors = child["authors"] as? String,
let year = child["year"] as? String,
let country = child["country"] as? String,
let createdAt = child["createdAt"] as? TimeInterval
else { return nil }
self.id = snapshot.key
self.isbn = isbn
self.title = title
self.authors = authors
self.year = year
self.country = country
self.createdAt = Date(timeIntervalSince1970: createdAt)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment