我试图将我从我的firebase数据库检索到的数据传递到我的单身人员的字段中。数据通过闭包接收,并在该闭包中传递一些数据到我的单身人士的属性。如果我在封闭内部打印数据结构(在分配了所有东西之后),我得到了我期望的输出,但是如果我在所有数据传入之后将其打印在初始化程序的末尾,则它是空的。如何将数据传递给从Firebase中检索信息的闭包?
import Foundation
import Firebase
class EmployeeList {
static let sharedInstance = EmployeeList()
var employeeDictionary: [String: [EmployeeData]]
var ref: DatabaseReference!
private init() {
employeeDictionary = [String: [EmployeeData]]()
ref = Database.database().reference()
ref.child("employeeList").observeSingleEvent(of: .value, with: { snapshot in
if let dictionary = snapshot.value as? [String: [String: AnyObject]] {
for subsection in dictionary {
var subsectionEmployees: [EmployeeData] = []
for item in subsection.value {
self.ref.child("employeeList/\(subsection.key)/\(item.key)").observeSingleEvent(of: .value, with: { employeeSnapshot in
let employeeObject = EmployeeData(snapshot: employeeSnapshot)
subsectionEmployees.append(employeeObject)
self.employeeDictionary[subsection.key] = subsectionEmployees
//print(self.employeeDictionary) This print statement prints out the expected data every time another employee is appended
})
}
}
}
//print(self.employeeDictionary) This print statement prints an empty data structure
})
}
}
这是因为当您从Firebase获取数据时,调用是异步的,因此外部打印会在之前调用。 –
请按照此链接(https://stackoverflow.com/questions/38364288/getting-data-out-of-a-closure-that-retrieves-data-from-firebase?rq=1) –