我从快照中获取所有数据,并使用该数据创建对象列表。 我的问题:我无法返回列表以在其他代码功能中使用我的对象。
我试图浏览列表以使用快照创建代码,以实现上面在代码中声明的对象的新列表。
class ViewController: UIViewController {
lazy var usersCollection = Firestore.firestore().collection("ship")
var ships: [MyShip] = []
override func viewDidLoad() {
super.viewDidLoad()
getUsers()
print(ships.count)
}
getData函数:
func getUsers() {
usersCollection.getDocuments { (snapshot, _) in
//let documents = snapshot!.documents
// try! documents.forEach { document in
//let myUser: MyUser = try document.decoded()
//print(myUser)
//}
let myShip: [MyShip] = try! snapshot!.decoded()
// myShip.forEach({print($0)})
for elt in myShip {
print(elt)
self.ships.append(elt)
}
print(self.ships[1].nlloyds)
}
}
控制台中的结果:
- my list is not filled return 0
- I print the objects well and I print them well
- I print the ships object[1].nloyds = 555 well in the function
答案 0 :(得分:0)
您的print(ships.count)
中的viewDidLoad
调用正在打印一个空数组,因为.getDocuments()
方法是异步的。尝试将getUsers
写成这样的闭包:
func getUsers(completion: @escaping ([MyShip]) -> Void) {
usersCollection.getDocuments { (snapshot, _) in
let myShip: [MyShip] = try! snapshot!.decoded()
completion(myShip)
}
}
,然后在viewDidLoad
方法中使用它,如下所示:
override func viewDidLoad() {
super.viewDidLoad()
getUsers() { shipsFound in
self.ships = shipsFound
print(self.ships.count)
}
}