快速地,如何使函数从Firebase返回querysnapshot? [英] In swift, how to make function to return querysnapshot from Firebase?
问题描述
迅速,如何在此代码中返回 querySnapshot
:
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())")
}
}
}
}
上面的代码从firebase读取数据,并在else语句中打印出数据.我想从视图控制器调用 read()
函数,并且 read()
应该返回 querySnaphot!.documents
.如果可以,我该怎么做:
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
推荐答案
void函数中意外的非void返回值
Unexpected non-void return value in void function
您不能在Clouser内部返回值.代替它,您可以使用完成处理程序.
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)
}
}
}
用法:
read { (documents) in
for document in documents{
print("\(document.documentID) => \(document.data())")
}
}
这篇关于快速地,如何使函数从Firebase返回querysnapshot?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!