我编写了一个函数来从CLLocation传递给CLGeocoder的地址。问题是埋藏在嵌套范围层下面的地址,我无法弄清楚如何将其退出函数。
func getAddress(_ location: CLLocation) {
CLGeocoder().reverseGeocodeLocation(location) {
(placemarks, error) in // placemarks stores address
if error != nil {
} else {
if placemarks != nil && placemarks!.count > 0 {
if let placemark = placemarks?[0]{
if placemark.subThoroughfare != nil { self.myAddress = placemark.subThoroughfare!}
if placemark.thoroughfare != nil { self.myAddress += " " + placemark.thoroughfare! }
if placemark.locality != nil { self.myAddress += "<br>" + placemark.locality! }
if placemark.postalCode != nil { self.myAddress += "<br>" + placemark.postalCode! }
} // close if placemark
} // close if placemarks.count
} // close if error
} // close clgeocoder
} // close getAddress
写入全局变量对我来说非常脆弱,我想创建一个更通用的getAddress()对象,该对象返回一个可选的字符串,然后可以被其他任何东西使用。
我理解我的问题因封闭执行的异步性而加剧。
所以我想学习......
a)在这种特定情况下如何将地址字符串传递出getAddress()
b)最佳传递嵌套值的通用方法,而不依赖于诸如全局变量之类的脆弱设计模式