问题
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