-3

I found this great piece of code for Reverse Geocoding in Swift 4 here: Reverse geocoding in Swift 4

I cannot understand what is going on here:

func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) -> ())  {
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { completion($0?.first, $1) }
}

After you call it from here:

geocode(latitude: -22.963451, longitude: -43.198242) { placemark, error in
 guard let placemark = placemark, error == nil else { return }
// you should always update your UI in the main thread
DispatchQueue.main.async {
    //  update UI here
    print("address1:", placemark.thoroughfare ?? "")
    print("address2:", placemark.subThoroughfare ?? "")
    print("city:",     placemark.locality ?? "")
    print("state:",    placemark.administrativeArea ?? "")
    print("zip code:", placemark.postalCode ?? "")
    print("country:",  placemark.country ?? "")       
 }
}

Can anyone offer an explanation.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Man James
  • 79
  • 1
  • 8

1 Answers1

0
# Gets latitude, longitude and a completion block
func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) -> ()) 
{
    # Calls system function to resolve the coordinates
    CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude))
    {
        # $0 is the placemarks array so this returns the first value of the placemarks array
        # $1 is the error 
        completion($0?.first, $1)

    }
}

Geocode function gets latitude and longitude and a completion block. It passes the coordinates to CLGeocoder().reverseGeocodeLocation function and returns the first placemark with the completion block.

Method signature for reverseGeocodeLocation is

func reverseGeocodeLocation(_ location: CLLocation, completionHandler: @escaping CLGeocodeCompletionHandler)

And the completion handler is defined as

typealias CLGeocodeCompletionHandler = ([CLPlacemark]?, Error?) -> Void

as you can see [CLPlacemark]? is an optional array of CLPlacemarks.

cekisakurek
  • 2,474
  • 2
  • 17
  • 28