iosswiftcoordinatesclgeocodercllocationcoordinate2d

Return CLLocationCoordinate2D to struct


I'm new in programming and my question is how to return data of variables type CLLocationCoordinate2D to Coordinates i.e. type of a structure. Trying to develop a weather app.

I have a struct:

struct Coordinates {
    let latitude: Double
    let longitude: Double
}

My code looks as follows:

//getting coordinates from String
func getCoordinateFrom(address: String, completion: @escaping(_ coordinate: CLLocationCoordinate2D?, _ error: Error?) -> () ) {
                CLGeocoder().geocodeAddressString(address) { placemarks, error in
                    completion(placemarks?.first?.location?.coordinate, error)
                }
            }

//When the User type his city, coordinates have type of CLLocationCoordinate2D    
@IBAction func changeCityButtonPressed(_ sender: UIButton) {
            guard let address = textField.text else { return }
            getCoordinateFrom(address: address) { coordinate, error in
                guard let coordinate = coordinate, error == nil else { return }
                DispatchQueue.main.async {
                    print(coordinate)
                }  
            }
        }

I've got a constant and my task is to transfer coordinates from function to this constant.

  let coordinates = Coordinates(latitude: 00.617366, longitude: 37.617366)

The problem is that these coordinates in function are in closure. So I can't return them or etc. I try to find the right answer but with no results. Anybody have some advice/solution?


Solution

  • on this line:

     let coordinates = Coordinates(latitude: 00.617366, longitude: 37.617366)
    

    replace let with var

    and in this code:

      @IBAction func changeCityButtonPressed(_ sender: UIButton) {
            guard let address = textField.text else { return }
            getCoordinateFrom(address: address) { coordinate, error in
                guard let coordinate = coordinate, error == nil else { return }
                DispatchQueue.main.async {
                    print(coordinate)
                }  
            }
        }
    

    replace this:

      guard let coordinate = coordinate, error == nil else { return }
                DispatchQueue.main.async {
                    print(coordinate)
                } 
    

    by this:

      guard let coordinate = coordinate, error == nil else { return }
                coordinates.latitude = coordinate.latitude
                coordinates.longitude = coordinate.longitude
                DispatchQueue.main.async {
                    print(coordinate)
                } 
    

    this is how your coordinates variable will be updated with new lat long