gpt4 book ai didi

swift - 为什么 Swift 不更新闭包外的变量?

转载 作者:搜寻专家 更新时间:2023-11-01 06:24:17 25 4
gpt4 key购买 nike

这是我正在使用的代码——问题是返回的 CLLocationCoordinate2D 对象中纬度和经度的值都是 -1,它们的初始化值。我错过了什么?

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 回答的补充,重构代码的一种可能方法是:

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 组件。

关于swift - 为什么 Swift 不更新闭包外的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26394699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com