Pass a type object instead of a type instance. Also, andUID:bad style.
func handleSnapshot<T: FirebaseType>(snapshot: FDataSnapshot?, forType type: T.Type) -> [T]? {
guard let snapshot = snapshot, dictionaries = snapshot.value as? [NSObject: AnyObject] else { return nil }
var objects = [T]()
for (uid, dictionary) in dictionaries {
let theUID = uid as? String ?? "No UID"
guard let dictionary = dictionary as? [NSObject: AnyObject] else { return nil }
if let object = T(fromDictionary: dictionary, uid: theUID) {
objects.append(object)
}
}
return objects
}
Using:
// Explicit type declaration is unnecessary but included for clarity.
let doodads: [Doodad]? = handleSnapshot(snapshot, forType: Doodad.self)
UPDATE
Another approach: add a method to the FirebaseTypeprotocol extension:
extension FirebaseType {
func arrayFromSnapshot(snapshot: FDataSnapshot?) -> [Self]? {
guard let snapshot = snapshot, dictionaries = snapshot.value as? [NSObject: AnyObject] else { return nil }
var objects = [Self]()
for (uid, dictionary) in dictionaries {
let theUID = uid as? String ?? "No UID"
guard let dictionary = dictionary as? [NSObject: AnyObject] else { return nil }
if let object = Self(fromDictionary: dictionary, uid: theUID) {
objects.append(object)
}
}
return objects
}
}
Using:
let doodads = Doodad.arrayFromSnapshot(snapshot)
source
share