如何在执行块后返回值? 迅速

我想从函数中获取值。 有function块。 当块执行时,函数已经返回值。 我尝试了很多不同的方法,但他们没有帮助我。 我使用了NSOperation和Dispatch。 该函数始终返回值,直到执行块为止。

  var superPlace: MKPlacemark! func returnPlaceMarkInfo(coordinate: CLLocationCoordinate2D) -> MKPlacemark? { let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) geocoder.reverseGeocodeLocation(location) { (arrayPlaceMark, error) -> Void in if error == nil { let firstPlace = arrayPlaceMark!.first! let addressDictionaryPass = firstPlace.addressDictionary as! [String : AnyObject] self.superPlace = MKPlacemark(coordinate: location.coordinate, addressDictionary: addressDictionaryPass) } } return superPlace } 

您不能简单地返回此处,因为reverseGeocodeLocation函数是异步运行的,因此您需要使用自己的完成块:

 var superPlace: MKPlacemark! func getPlaceMarkInfo(coordinate: CLLocationCoordinate2D, completion: (superPlace: MKPlacemark?) -> ()) { let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) geocoder.reverseGeocodeLocation(location) { (arrayPlaceMark, error) -> Void in if error == nil { let firstPlace = arrayPlaceMark!.first! let addressDictionaryPass = firstPlace.addressDictionary as! [String : AnyObject] self.superPlace = MKPlacemark(coordinate: location.coordinate, addressDictionary: addressDictionaryPass) completion(superPlace: superPlace) } else { completion(superPlace: nil) } } } 

这种情况一遍又一遍地出现。 简短的回答是“你做不到”。

函数返回时,结果不可用。 异步调用发生在后台。

你想要做的是重构你的returnPlacemarkInfo函数来完成闭包。

我最近一直在Objective-C工作,所以我的Swift有点生疏,但它可能看起来像这样:

  func fetchPlaceMarkInfo( coordinate: CLLocationCoordinate2D, completion: (thePlacemark: MKPlacemark?) -> () ) { } 

然后当你调用它时,传入一个完成闭包,一旦地标可用就会被调用。

编辑:

我写了一个演示项目并将其发布在Github上,模拟处理异步网络下载。 看一眼

https://github.com/DuncanMC/SwiftCompletionHandlers

具体看一下方法asyncFetchImage() ,它几乎完全符合我们所说的:在内部使用异步方法,并在完成异步加载后获取它调用的完成块。