Skip to content

Instantly share code, notes, and snippets.

@calebhicks
Created October 28, 2015 22:34
Show Gist options
  • Save calebhicks/568aaeab1757db5f2ae4 to your computer and use it in GitHub Desktop.
Save calebhicks/568aaeab1757db5f2ae4 to your computer and use it in GitHub Desktop.
A simple Swift protocol for Firebase objects with default save() and delete() implementations.
//
// FirebaseType.swift
//
import Foundation
import Firebase
protocol FirebaseType {
// properties
var identifier: String? { get set }
var endpoint: String { get }
var secondaryEndpoints: [String]? { get }
var jsonValue: [String: AnyObject] { get }
// initializers
init?(json: [String: AnyObject], identifier: String)
// functions
mutating func save()
func delete()
}
extension FirebaseType {
mutating func save() {
// save to primary endpoint
var endpointBase: Firebase
if let childID = self.identifier {
endpointBase = FirebaseController.base.childByAppendingPath(endpoint).childByAppendingPath(childID)
} else {
endpointBase = FirebaseController.base.childByAppendingPath(endpoint).childByAutoId()
self.identifier = endpointBase.key
}
endpointBase.updateChildValues(self.jsonValue)
// save to any secondary endpoints
if let secondaryEndpoints = secondaryEndpoints {
for endpoint in secondaryEndpoints {
let secondaryEndpointBase = FirebaseController.base.childByAppendingPath(endpoint).childByAppendingPath(self.identifier)
secondaryEndpointBase.setValue(self.identifier)
}
}
}
func delete() {
let endpointBase: Firebase = FirebaseController.base.childByAppendingPath(endpoint).childByAppendingPath(self.identifier)
endpointBase.removeValue()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment