为什么在这段代码中我会得到 "Unexpected non-void return value in void function"

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

下面是代码:

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) 在它自己的闭包和函数中。当您使用这样的回调时,您不能 return 这样的值。但是,如果您确定该函数 return 立即是一个值,您可以执行以下操作:

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
}

您需要在您的函数中添加一个回调参数,您可以在 reverseGeocodeLocation 完成后调用该参数并将 pm 作为参数传递。

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
}