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