0

I've written a function to get an address from a CLLocation passed to CLGeocoder. The problem is the address in buried beneath layers of nested scope and I cannot figure out how to return it out of the function.

func getAddress(_ location: CLLocation) {

    CLGeocoder().reverseGeocodeLocation(location) {

        (placemarks, error) in       // placemarks stores address


        if error != nil {


        } else {

            if placemarks != nil && placemarks!.count > 0 {

                if let placemark = placemarks?[0]{

                    if placemark.subThoroughfare    != nil { self.myAddress = placemark.subThoroughfare!}

                    if placemark.thoroughfare       != nil { self.myAddress += " " + placemark.thoroughfare! }

                    if placemark.locality           != nil { self.myAddress += "<br>" + placemark.locality! }

                    if placemark.postalCode         != nil { self.myAddress += "<br>" + placemark.postalCode! }

                } // close if placemark

            } // close if placemarks.count

        } // close if error

    } // close clgeocoder

} // close getAddress

Writing to global variables strikes me a very brittle, and I want to make a more generic getAddress() object that returns an optional string that can then be used by anything else.

I understand that my problem is exacerbated by the asynchronicity of closure execution.

So I want to learn...

a) how pass the address string out of getAddress() in this specific case

b) the generic approach to best pass nested values out without relying on brittle design patterns like global variables

niblettes
  • 165
  • 1
  • 8
  • 2
    See http://stackoverflow.com/questions/27081062/swift-how-do-i-return-a-value-within-an-asynchronous-urlsession-function It's essentially the same question and Rob's answer is just what you need to do. – rmaddy Mar 23 '17 at 02:58
  • 1
    Unrelated: instead of `if x != nil { /* use x! */ }`, you should just use conditional binding: `if let x = x { /* use x */ }` – Alexander Mar 23 '17 at 03:15
  • Thanks Alexander, i know that is more swifty, but I find it less readable for simple variable value assignments. But I should get over old habits. – niblettes Mar 23 '17 at 07:34
  • Maddy, thanks -- i had read that thread before. But the code is over 3 years old and Swift has changed a lot in that time. Plus I think i need more detailed explanation of the design patterns used to pass calculated values up through the nesting. I encounter this situation a lot and need to better understand how to handle it on a conceptual level as well as at the code level (I am learning swift). – niblettes Mar 23 '17 at 07:40

0 Answers0