Swift为什么不更新闭包之外的变量? [英] Why does Swift not update the variables outside the closure?
本文介绍了Swift为什么不更新闭包之外的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我使用的代码-问题是返回的CLLocationCoordinate2D对象中的纬度和经度值均为-1,即它们的初始化值。我缺少什么?
Here's the code I'm using -- Problem is that the value of latitude and longitude in the returned CLLocationCoordinate2D object are both -1, their initialized values. What am I missing?
func getLocationInfoForAddress(shop: store) -> CLLocationCoordinate2D {
var address = getAddressInOneLine(shop)
var latitude: CLLocationDegrees = -1
var longitude: CLLocationDegrees = -1
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, {(placemarks: [AnyObject]!, error: NSError!) -> Void in
if let placemark = placemarks?[0] as? CLPlacemark {
latitude = placemark.location.coordinate.latitude
longitude = placemark.location.coordinate.longitude
}
})
var location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude,longitude: longitude)
return location
}
推荐答案
作为@NateCook答案的补充,一种重构代码的可能方法是:
As a complement to @NateCook's answer, one possible way to refactor your code is:
func getLocationInfoForAddress(shop: store) {
var address = getAddressInOneLine(shop)
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, {(placemarks: [AnyObject]!, error: NSError!) -> Void in
if let placemark = placemarks?[0] as? CLPlacemark {
var latitude = placemark.location.coordinate.latitude
var longitude = placemark.location.coordinate.longitude
var location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude,longitude: longitude)
self.didReceiveGeocodeAddress(location)
}
})
}
func didReceiveGeocodeAddress(location: CLLocationCoordinate2D) {
// do something
}
获取位置后,您将调用相同的方法类传递位置。由于处理程序关闭是在主线程中执行的,因此可以安全地更新UI组件。
When the location is obtained, you invoke a method of the same class passing the location. Since the handler closure is executed in the main thread, you can safely update UI components.
这篇关于Swift为什么不更新闭包之外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文