gpt4 book ai didi

ios - 将值传递给闭包函数

转载 作者:行者123 更新时间:2023-11-28 15:37:54 25 4
gpt4 key购买 nike

检查这段代码:

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")
}
})
}

在 View Controller 中

override func viewDidLoad() {
var addressInViewController = String()
getReversedGeocodeLocation(location: location, completionHandler: {
print("After geo finished")
})
}

这是一个使用闭包的简单案例。如您所见,当反向地理完成时,它会更新在函数本身之外定义的 addressInViewController 变量。关于闭包,我有点困惑,但我知道它本质上是将另一个函数作为参数传递给一个函数。那么我是否可以传入类似 (_ String: 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

})
}

根据您的需要制作 Value 的数据类型。

关于ios - 将值传递给闭包函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44108618/

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