Steven
Steven

Reputation: 31

Swift Return value

So I'm making an app that show's a map and your current location. Now I have made a button and when I press the button it should make a marker (annotation) on my location.

So I have this function that grabs my current location so that I can show this on the map.

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations.last

    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.mapView.setRegion(region, animated: true)

    self.locationManager.stopUpdatingLocation()

    return center
}

Now I want to use the data of the variable "Center" in another function. But when I "return center". I get the following error: "Unexpected non-void return value in void function"

I googled a lot and I've searched stack overflow. But I'm very new with swift. And can't seem to find or understand how to fix it.

I hope some one can help me and explain to me how I should fix this!

Thanks in advance!

Upvotes: 0

Views: 105

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

Since you want to return center which is a CLLocationCoordinate2D, your function signature has to explicitly return a CLLocationCoordinate2D, like this:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) -> CLLocationCoordinate2D {

    let location = locations.last

    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.mapView.setRegion(region, animated: true)

    self.locationManager.stopUpdatingLocation()

    return center
}

Without -> CLLocationCoordinate2D in the signature, the function is assumed to return Void, hence the error message you got.

Upvotes: 1

Related Questions