Ios 将值传递给闭包函数
查看此代码:Ios 将值传递给闭包函数,ios,swift,closures,Ios,Swift,Closures,查看此代码: func getReversedGeocodeLocation(location: CLLocation, completionHandler: @escaping ()->()) { CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in if error != nil { prin
func getReversedGeocodeLocation(location: CLLocation, completionHandler: @escaping ()->()) {
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks != nil {
if placemarks!.count > 0 {
let pm = placemarks![0]
if let addressDictionary: [AnyHashable: Any] = pm.addressDictionary,
let addressDictionaryFormatted = addressDictionary["FormattedAddressLines"] {
let address = (addressDictionaryFormatted as AnyObject).componentsJoined(by: ", ")
self.addressInViewController = address
}
completionHandler()
}
} else {
print("Problem with the data received from geocoder")
}
})
}
在viewController中
override func viewDidLoad() {
var addressInViewController = String()
getReversedGeocodeLocation(location: location, completionHandler: {
print("After geo finished")
})
}
这是一个使用闭包的简单例子。如您所见,当反向geo完成时,它会更新在函数本身外部定义的addressInViewController变量。谈到闭包,我有点困惑,但我知道它本质上是将另一个函数作为参数传递到函数中。那么,我可以传入像ustring:x->而不是->这样的东西吗?地址变量将从主反向地理函数填充并传递到哪里?我试过这么做,但它说x是未定义的。如果这是可以实现的,那么我想我可以使用闭包以更好的方式解耦代码
谢谢,祝你度过愉快的一天:像这样定义你的方法
func getReversedGeocodeLocation(location: CLLocation, completionHandler: @escaping (_ value : Any)->()) {
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks != nil {
if placemarks!.count > 0 {
let pm = placemarks![0]
if let addressDictionary: [AnyHashable: Any] = pm.addressDictionary,
let addressDictionaryFormatted = addressDictionary["FormattedAddressLines"] {
let address = (addressDictionaryFormatted as AnyObject).componentsJoined(by: ", ")
self.addressInViewController = address
}
completionHandler(address)
}
} else {
print("Problem with the data received from geocoder")
}
})
}
override func viewDidLoad() {
var addressInViewController = String()
getReversedGeocodeLocation(location: location, completionHandler: { (_ values : Any) in
self. addressInViewController = values
})
}
根据您的需要创建值的数据类型