In swift, how to make function to return querysnapshot from Firebase?

雨燕双飞 提交于 2020-02-06 06:36:09

问题


In swift, how can I return a the querySnapshot in this code:

  func read(){
    reference(to: .users).getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")

            }
        }

    }
}

The above code reads the data from firebase and prints the data out in the else statement. I want to call the read() function from a view controller and read() should return the querySnaphot!.documents. How can I do this if I do:

func read() -> QuerySnaphot{
...
return querySnapshot!.documents

It gives me an error that it returns a non void value


回答1:


Unexpected non-void return value in void function

You cannot return a value inside the clouser. Instead of it you can use completion handlers.

 func read(_ completion:@escaping(_ querySnapshot:[QueryDocumentSnapshot])->Void){
   reference(to: .users).getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {

            if let documents = querySnapshot?.documents{
                completion(documents)
            }
        }

    }

Usage:

read { (documents) in

    for document in documents{

          print("\(document.documentID) => \(document.data())")
     }
}


来源:https://stackoverflow.com/questions/50458752/in-swift-how-to-make-function-to-return-querysnapshot-from-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!