为什么在这段代码中我会得到" void函数中出现意外的非void返回值"

时间:2016-02-19 00:16:53

标签: ios xcode swift optional optional-parameters

以下是代码:

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
}

2 个答案:

答案 0 :(得分:1)

GCAnnotation.geocoder.reverseGeocodeLocation(clLocation)在它自己的闭包和函数中。当您使用类似的回调时,您无法返回类似的值。但是,如果您确定该函数立即返回值,则可以执行以下操作:

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
}

答案 1 :(得分:1)

您需要在函数中添加一个回调参数,您可以在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
}