Pierre Prevalon Pierre Prevalon - 7 months ago 36
Swift Question

How to use coordinates outside of didUpdateLocation function in Swift?

I'm trying to use the coordinates outside of

didUpdateLocations
function but I can not get it to work. I try to declare the coordinates as a degree outside of the function but that does not work. How can I get some guidance on this?

var currentUserLatitude:CLLocationDegrees?
var currentUserLongitude:CLLocationDegrees?

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
//location info about the user
let location = locations.last
let center = CLLocationCoordinate2D(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!)
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: center, span:span)
self.mapView.setRegion(region, animated: true)
// i want to use these variables outside the function
var currentUserLatitude = location!.coordinate.latitude
var currentUserLongitude = location!.coordinate.longitude

}

Answer

If you want to assign values to the variables declared outside the local function, don't redeclare the variables as local variables.

Change these lines:

var currentUserLatitude = location!.coordinate.latitude
var currentUserLongitude = location!.coordinate.longitude

to:

currentUserLatitude = location!.coordinate.latitude
currentUserLongitude = location!.coordinate.longitude
Comments