简体   繁体   中英

why in this code would I be getting “Unexpected non-void return value in void function”

Here is the code below:

private func getReverseGeocodeData(newCoordinates : CLLocationCoordinate2D) -> CLPlacemark? {
  let clLocation = CLLocation(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude)
  GCAnnotation.geocoder.reverseGeocodeLocation(clLocation) { placemarks, error in
    if let pms = placemarks {
      let pm : CLPlacemark? = pms.first as CLPlacemark?
      return pm // ==> "Unexpected non-void return value in void function"
    }
  }
  return nil
}

GCAnnotation.geocoder.reverseGeocodeLocation(clLocation) is in it's own closure and function. When you use a callback like that you can't return a value like that. However if you are sure that that function returns a value immediately you could the following:

private func getReverseGeocodeData(newCoordinates : CLLocationCoordinate2D) -> CLPlacemark? {
    let pm: CLPlacemark?
    let clLocation = CLLocation(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude)
    GCAnnotation.geocoder.reverseGeocodeLocation(clLocation) { placemarks, error in
        if let pms = placemarks {
             pm = pms.first as CLPlacemark?
        }
    }
    return pm
}

You need to add a callback parameter in your function that you can call after the reverseGeocodeLocation is finished and pass the pm as parameter.

private func getReverseGeocodeData(callback : (CLPlaceMark?)-> Void, newCoordinates : CLLocationCoordinate2D) -> CLPlacemark? {
  let clLocation = CLLocation(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude)
  GCAnnotation.geocoder.reverseGeocodeLocation(clLocation) { placemarks, error in
    if let pms = placemarks {
      let pm : CLPlacemark? = pms.first as CLPlacemark?
       callback(pm)
    }
  }
  return nil
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM