从Swift中的回调中返回对象 [英] Returning object from callback in Swift
问题描述
我想用其他逻辑将geocoder.geocdeAddressString包装在另一个方法中。
I want to wrap the geocoder.geocdeAddressString in another method with other logic.
public func placemarkForSearchResult<T>(searchResult: T) -> CLPlacemark? {
if let searchResult = searchResult as? String {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(searchResult, completionHandler: {
(placemarks, error) -> Void in
// Check for returned placemarks
if let placemarks = placemarks where placemarks.count > 0 {
return placemarks[0] as! CLPlacemark // CLPlacemark is not convertible to void error message
}
return nil // Typd Void does not conform to protocol NilLiteralConvertible
})
}
}
我在这个方法中有一些其他逻辑并不是真的相关,但我想知道如何处理这样的情况,我想返回一个CLPlacemark,但不能因为地理编码器的completionHandler返回虚空。我无法更改地理编码器回调的Void参数。那可能吗?或者我是否一直在调用使用地理编码器中找到的CLPlacemark的委托方法?提前致谢。
I have some other logic in this method that's not really relevant, but I was wondering how I can handle a situation like this where I want to return a CLPlacemark, but cannot because the completionHandler for the geocoder returns Void. I cannot change the Void parameter of the geocoder callback. Is that possible? Or am I stuck with calling a delegate method that uses the found CLPlacemark from the geocoder? Thanks in advance.
推荐答案
您永远不能从 placemarkForSearchResult
函数返回地标,因为获取地标需要使用异步函数( geocodeAddressString
)。到那个时候该函数已经完成并回调到你的完成处理程序,你的 placemarkForSearchResult
已经完成并且很久以前就已经返回了!
You can never return a placemark from your placemarkForSearchResult
function, because obtaining a placemark requires the use of an asynchronous function (geocodeAddressString
). By that time that function has finished and calls back into your completion handler, your placemarkForSearchResult
has already finished and returned long ago!
您需要一个与您正在调用的函数的异步特性兼容的策略。而不是从 placemarkForSearchResult
返回地标,您需要 placemarkForSearchResult
来接受回调函数参数 。当您在完成处理程序中有地标时,调用该回调函数。如果该回调函数(巧妙地)设计为接受地标参数,那么您现在将该地标交给任何一个打电话给您的人。
You need a strategy compatible with the asynchronous nature of the function you are calling. Instead of returning a placemark from placemarkForSearchResult
, you need placemarkForSearchResult
to accept a callback function parameter. When you have your placemark in the completion handler, you call that callback function. If that callback function is (cleverly) designed to accept a placemark parameter, you are now handing that placemark to whoever called you in the first place.
这篇关于从Swift中的回调中返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!