我在地圖中的幾個位置反轉地理代碼,我想將它包裝到一些常用方法。我所擁有的是以此爲出發點的工作原理:回調,具有多個參數的快速完成處理程序
func reverseGeocodeLocation(location: CLLocation, completion: (CLPlacemark) -> Void) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) {
(placemarks, error) -> Void in
// Check for returned placemarks
if let placemarks = placemarks where placemarks.count > 0 {
let topResult = placemarks[0] as! CLPlacemark
completion(topResult)
}
}
}
但是,如果我想添加其他參數我完成方法,將錯誤返回到我的觀點,像這樣:
func reverseGeocodeLocation(location: CLLocation, completion: (CLPlacemark, NSError) -> Void) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) {
(placemarks, error) -> Void in
// Check for returned placemarks
if let placemarks = placemarks where placemarks.count > 0 {
let topResult = placemarks[0] as! CLPlacemark
completion(topResult, error)
}
}
}
如果錯誤是nil
,那麼我的completion(topResult, error)
將失敗,因爲錯誤是零,並且訪問不良。但我不能這樣做,因爲參數不匹配完成處理程序。
if error != nil {
completion(topResult)
} else {
completion(...) // do something with the error
}
所以,如果我有一個零錯誤,我將如何調用我的完成處理程序?謝謝。
我認爲錯誤應該是可選的在這種情況下?什麼是geocoder.reverseGeocodeLocation方法的完整簽名? – Shripada