将值传递给闭包函数

时间:2017-05-22 08:54:48

标签: ios swift closures

查看此代码:

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

这是使用闭包的简单案例。如您所见,当反向地理完成时,它会更新在函数本身之外定义的addressInViewController变量。关于闭包我有点困惑,但我知道它实际上是将另一个函数作为参数传递给函数。那么我可以传递类似(_ String:x) - >()而不是() - >(),其中地址变量将从主反向地理函数填充并传递?我试过这样做,但它说“x”未定义。如果这是可实现的,那么我想我可以使用闭包以更好的方式解耦我的代码。

谢谢,祝你有个美好的一天:)

1 个答案:

答案 0 :(得分:1)

定义你的方法

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的数据类型。