无法为闭包内部的变量赋值 [英] Can't assign a value to variable inside of closure Swift
问题描述
我正在尝试从Firebase获取属于特殊用户的当前文档数.每当我尝试将计数值分配给闭包中的变量时,值始终显示为nill.因此,我进行了一些研究,结果我发现联网有时会花费很长时间,并且异步发生.因此,如果我没错,因为异步返回值时,可能会在赋值之前在函数内部返回一个值.
I'm trying to get current document count belongs to spesific user from Firebase. Whenever i try to assign count value to my variable in closure, value is always shown as nill. So that i did couple of research, as a result i figured out networking sometimes takes so long and it happens asynchronously. So if i'm not wrong due to asynchronous returning a value inside a fucntion might happen before assign value .
我试图添加dispatchqueue.main.async,但是对我来说不起作用...
I tried to add dispatchqueue.main.async but it didn't work for me...
这是我的代码
func getEventCount () -> Int? {
var count: Int?
db.collection("Events").whereField("owner", isEqualTo: currentUser.email).getDocuments { (snapshot, error) in
if error != nil {
print(error)
}else {
DispatchQueue.main.async {
if let snapshot = snapshot {
count = snapshot.count
}
}
}
}
return count
}
我的主要目标是从数据库获取计数数据并将其分配给"count"变量.那么,为什么我需要该计数变量?因为我要将该计数值传递给tableView数据源方法numberOfRowsInSection,该方法需要一个int值.使用该值,我将在表视图中表示来自Firestore的事件"文档中的一些数据.
注意:当我尝试在闭包中打印计数值时,它会显示所需的值,但是当函数返回值时,它会显示nill ...
note: When i try to print count value in closure it shows desired value, but when function return value it's shown nill...
推荐答案
一旦它是异步调用,您就无法从函数中同步返回值.您应该接受将接受计数的函数的回调.该回调函数或闭包将异步传递该值.
Once it is a Async call - you cannot synchronously return the value from the function. You should accept a callback to the function that will accept the count. That callback function or closure will be passed the value asynchronously.
func getEventCount (callback: @escaping(Result<Int, Error>) -> Void) {
db.collection("Events").whereField("owner", isEqualTo: currentUser.email).getDocuments { (snapshot, error) in
if error != nil {
let result = Result.failure(error)
callback(result)
}else if let snapshot = snapshot {
let result = Result.success(snapshot.count)
callback(result)
} else {
let result = Result.failure(SomeCustomAppError)
callback(result)
}
}
}
然后您可以通过回调函数调用此函数
Then you can call this function passing in a callback
self.getCount() { result in
switch result {
case .success(let count): /// use count
print(count)
// only here u can assign the count value to ur variable
case .error(let error): /// handle error
print(error.localizedDescription)
}
}
注意:在上面,我使用了Swift标准库中的Result数据类型- https://developer.apple.com/documentation/swift/result ,以便两者均出错或结果可以传回
Note: In the above I've used the Result datatype from Swift standard library - https://developer.apple.com/documentation/swift/result so that both error or result can be passed back
这篇关于无法为闭包内部的变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!