arrays - Firestore 使用数据恢复 Swift 5.0 实例化对象
问题描述
我从我的快照中获取所有数据并使用数据创建一个对象列表。我的问题:我无法返回列表以在其他代码函数中使用我的对象。
我试图浏览我的列表以使用我的快照创建以实现上面在我的代码中声明的新对象列表。
class ViewController: UIViewController {
lazy var usersCollection = Firestore.firestore().collection("ship")
var ships: [MyShip] = []
override func viewDidLoad() {
super.viewDidLoad()
getUsers()
print(ships.count)
}
获取数据函数:
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
解决方案
您的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)
}
}
推荐阅读
- sql-server - SQLLocalDB.exe 信息 - 返回错误代码 15100 等
- java - 将图像上传到 AWS S3 存储桶并使用 Amazon CloudFront 签名的 url 提供该图像
- php - 尝试在 PHP 中使用命名空间时的未知问题
- django - Django RF,序列化程序验证字段中的日期比较错误
- python - 从整数中减去浮点数将返回一个终止数字
- python - 可以在命令提示符和脚本中导入 py2exe,但由于“找不到模块错误”而无法在命令提示符处运行 setup.py。
- jenkins - 将 gitlab 与 jenkins 集成时 404 Not found
- shell - 为什么shell忽略星号glob
- php - 在 WooCommerce 中按运输区域添加运输方式
- android - android-为运行时权限创建阻塞调用