我打算使用一个类从Firebase数据库检索条目。那里的方法包括例如getAllProducts() -> [Product]
和getProductsByCategory(category:) -> [Product]
。
在这些方法中,我从Firebase调用observeSingleEvent()
方法以在特定路径上获取快照-可以正常工作。
现在,这样我就不必在上述方法之一中创建产品对象时重复我自己了:
class FirebaseFactory {
self.ref.child("products").observeSingleEvent(of: .value) { (snapshot) in
var products = [Product]()
for product in snapshot.children.allObjects as! [DataSnapshot] {
let productToAdd = self.createProduct(product)
}
}
助手类createProduct()
如下所示:
func createProduct(productSnapshot: DataSnapshot) -> Product? {
let identifier = productSnapshot.key
if let ean = productSnapshot.childSnapshot(forPath: "ean").value as? Int,
let name = productSnapshot.childSnapshot(forPath: "name").value as? String,
let category = productSnapshot.childSnapshot(forPath: "category").value as? String,
let productCategory = Category(rawValue: category){
let product = Product(identifier: identifier, category: productCategory, ean: ean, name: name)
return product
}
return nil
}
现在,即使for
-Loop中的产品对象的类型为DataSnapshot
,而我的助手函数也希望它作为参数,Xcode会向我显示失败
'DataSnapshot' is not convertible to 'FirebaseFactory'
,
其中FirebaseFactory
是我的自定义类,所有这些方法都位于...
类的概述在这里(省略了更多方法):
class FirebaseFactory {
/// Captures all available products in an array
func getAvailableProducts(completion: @escaping ([Product]) -> Void) {
self.ref.child("products").observeSingleEvent(of: .value) { (snapshot) in
var products = [Product]()
for product in snapshot.children.allObjects as! [DataSnapshot] {
let productToAdd = self.createProduct(product)
products.append(productToAdd)
}
}
completion(products)
}
/// Helper function to create a product from the Firebase Node
func createProduct(productSnapshot: DataSnapshot) -> Product? {
let identifier = productSnapshot.key
if let ean = productSnapshot.childSnapshot(forPath: "ean").value as? Int,
let name = productSnapshot.childSnapshot(forPath: "name").value as? String,
let category = productSnapshot.childSnapshot(forPath: "category").value as? String,
let productCategory = Category(rawValue: category){
let product = Product(identifier: identifier, category: productCategory, ean: ean, name: name)
return product
}
return nil
}
}
知道这里发生了什么吗?