arrays - Firestore实例化对象与数据恢复Swift 5.0

标签 arrays swift firebase google-cloud-firestore instantiation

我从快照中获取所有数据,并使用这些数据创建一个对象列表。 我的问题:我无法返回列表以在其他代码函数中使用我的对象。

我尝试浏览我的列表以使用我的快照创建,以实现上面在我的代码中声明的新对象列表。

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)
    }
}

result console

控制台结果:

- 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 

最佳答案

您在 viewDidLoad 中的 print(ships.count) 调用正在打印一个空数组,因为 .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)
    }

}

关于arrays - Firestore实例化对象与数据恢复Swift 5.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759712/

相关文章:

C:将二维数组分配给另一个数组

json - 无法获取 JSON 对象的长度

android - 如何在我的 android 应用程序中使用 firebase 集成 otp 验证

ios - Swift:在多个 View Controller 和数组之间保持数据副本一致

c - Str[Col][Row] 中的 Str 是 "pointer"还是 "pointer to pointer"?

c - C中的二维字符串数组

ios - 使用 MKZoomScale 调整 MKAnnotationView 的大小 - Swift 2.0

ios - 如何在SCNSphere对象上应用脉冲效果?

swift - Swift 中对闭包的弱引用

javascript - Firebase Firestore FCM 消息发送问题