我无法创建从 Firebase 数据库返回 Product 对象数组的函数。
我尝试使用闭包中的开关将变量设置为其各自的名称,然后在设置所有变量后实例化该对象。我尝试使用闭包的范围来尝试访问“检索到的值”。下面是我的 Firebase 数据库、产品对象和函数的快照。
func createArray() -> [Product] {
var newArray = [Product]()
let ref = Database.database().reference()
var productName = String()
var productHealth = String()
var productPrice = 0
var productImage = String()
for bigIndex in 0..<7 {
for smallIndex in 0..<4{
ref.child("masterSheet/\(bigIndex)/\(smallIndex)").observeSingleEvent(of: .value) { (snapshot) in let retrievedValue = snapshot.value}
//I used to have a switch statement here that went like
//switch smallIndex{ case 0: productPrice = retrievedValue as! String }
}
let completeProduct = Product(productName: productName, productHealth: productHealth, productPrice: productPrice, productImage: productImage)
newArray.append(completeProduct)
}
return newArray
}
产品对象:
import Foundation
import UIKit
class Product {
var productName: String
var productHealth: String
var productPrice: Int
var productImage: String
init(productName: String, productHealth: String, productPrice: Int, productImage: String ){
self.productName = productName
self.productHealth = productHealth
self.productPrice = productPrice
self.productImage = productImage
}
}
我的目标是生成数据库中所有项目的数组。
最佳答案
您需要从smallIndex中获取值并将其设置到modelClass Product
中,如下所示:
func createArray() -> [Product] {
var newArray = [Product]()
let ref = Database.database().reference()
for bigIndex in 0..<7 {
for smallIndex in 0..<4{
ref.child("masterSheet/\(bigIndex)/\(smallIndex)").observeSingleEvent(of: .value) { (snapshot) in let retrievedValue = snapshot.value}
//I used to have a switch statement here that went like
//switch smallIndex{ case 0: productPrice = retrievedValue as! String
let singleProduct = Product()
singleProduct.productName = "fetch value from small index"
singleProduct.productPrice = retrievedValue
sigleProduct.productHealth = "fetch value from small index"
newArray.append(singleProduct)
}
}
}
return newArray
}
关于ios - 如何使用 Firebase 数据库填充对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57231179/