Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Google Maps iOS SDK code in Swift do?

I'm following a raywenderlich.com tutorial on using the Google Maps iOS SDK. I came across this piece of code which is halfway down this link here: https://www.raywenderlich.com/109888/google-maps-ios-sdk-tutorial.

I am familiar with Swift but I do not get what the piece of code after geocoder.reverseGeocodeCoordinate(coordinate) does; specifically, how can you just place the curly brackets right after the method call and what does it accomplish? I am asking this in terms of Swift syntax.

func reverseGeocodeCoordinate(coordinate: CLLocationCoordinate2D) {

  // 1
  let geocoder = GMSGeocoder()

  // 2
  geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
    if let address = response?.firstResult() {

      // 3
      let lines = address.lines as! [String]
      self.addressLabel.text = lines.joinWithSeparator("\n")

      // 4
      UIView.animateWithDuration(0.25) {
        self.view.layoutIfNeeded()
      }
    }
  }
}
like image 209
JoeW467 Avatar asked Jun 15 '26 11:06

JoeW467


1 Answers

It is called a trailing closure. A trailing closure is a closure expression that is written outside of the parentheses of the function call.

The only requirement here is that the closure must be function's final argument.

Given the following function, these two calls are identical:

func someAPICall(url: String, completion: (Bool -> Void)) {
  // make some HTTP request
  completion(result.isSuccess)
}

someAPICall("http://httpbin.org/get") { success in
  print("Success", success)
}

someAPICall("http://httpbin.org/get", completion: { success in
  print("Success", success)
})
like image 186
Ozgur Vatansever Avatar answered Jun 17 '26 23:06

Ozgur Vatansever