1

I want to be able to use the latitude string outside of the function getLatitude. I have tried to just enter "return latstring" but this didn't work because it is like one layer deeper??? However I have no clue how to fix this. Here is the code:

private func getLatitude() -> String {
        let address = "Oslo"
        let geoCoder = CLGeocoder()
        geoCoder.geocodeAddressString(address) { (placemarks, error) in
            guard
                let placemarks = placemarks,
                let location = placemarks.first?.location
            else { return }
            // do whatever you want with CLLocation object
            
            
            
            let latitude = location.coordinate.latitude
            
            let latstring = String(latitude)
            
            
            return(latstring)
            // CLLocationCoordinate2D(latitude: 40.7129822, longitude: -74.007205)
        }
       }
  • 1
    Read something about asynchronous operations/tasks, like https://michaellong.medium.com/how-to-chain-api-calls-using-swift-5s-new-result-type-and-gcd-56025b51033c – Asperi Dec 24 '20 at 11:41
  • 1
    Different API, same issue: You cannot return something from inside an asynchronous task as the closure doesn't have a return value. – vadian Dec 24 '20 at 11:50
  • Won't let latstring = getLatitude(); work?. It will copy returning value to new variable – abh Dec 24 '20 at 12:08
  • @Babar No, it won't. The code doesn't even compile. – vadian Dec 24 '20 at 12:17

1 Answers1

1

Declare a variable outside of function and Initialise it to the whatever value you want inside the function.