swift中void函数中的dispatch_async和意外的非void返回值 [英] dispatch_async and unexpected non-void return value in void function in Swift
问题描述
我的 appDelegate
中有一个函数可以返回用户的当前位置。
I have a function in my appDelegate
that returns user's current location.
现在我想调用它在其他地方异步,我做了:
Now I want to call it asynchronously at some other place and I did:
func handleLocation() -> CLLocation {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.startGPS()
while (!appDelegate.isLocationFixed()) {
sleep(1)
}
dispatch_async(dispatch_get_main_queue()) {
return appDelegate.getLocation()
}
}
}
但现在这行返回appDelegate.getLocation()
给我带来错误:
but now this line return appDelegate.getLocation()
brings me the error:
void函数中意外的非void返回值
unexpected non-void return value in void function
我不太了解中的线程Swift
但是,你能帮我解决这个问题吗?
I don't know too much about threads in Swift
yet, could you help me with fixing this issue?
推荐答案
问题是
dispatch_async(dispatch_get_global_queue(priority, 0)) {
和
dispatch_async(dispatch_get_main_queue()) {
实际上是创建闭包/函数,因此其中的任何代码都与该函数有关,而不是
are actually creating closures/functions, so any code within them will relate to that function, not
func handleLocation() -> CLLocation {
如果你在函数中进行异步操作,你真的不能拥有异步操作完成后的return语句。相反,您应该在函数中使用完成处理程序。例如:
If you're doing an asynchronous operation within a function, you can't really have a return statement after the asynchronous operation is completed. Instead, you should use a completion handler in your function. e.g.:
func aSyncFunction(completionHandler: (AnyObject) -> ()) {
//do async opporation
completionHandler("finished") // call the completion block when finished
}
以下是我将如何为您的用例实现它:
Here's how I would implement it for your use case:
func handleLocation(completionBlock: (CLLocation?) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
guard let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate else {
dispatch_async(dispatch_get_main_queue()) {
completionBlock(nil)
}
return
}
appDelegate.startGPS()
while (!appDelegate.isLocationFixed()) {
sleep(1)
}
dispatch_async(dispatch_get_main_queue()) {
completionBlock(appDelegate.getLocation())
}
}
}
示例用法:
handleLocation { (location: CLLocation?) in
if let location = location {
//use valid location
}
}
这篇关于swift中void函数中的dispatch_async和意外的非void返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!