2

我使用了在 swift 1.0 中工作的函数 geocodeAddressString,但在 swift2 中没有。谁能告诉我我的代码有什么问题以及如何解决这个问题?谢谢!

geocoder.geocodeAddressString(address, {(placemarks: [AnyObject], error: NSError) -> Void in  //Error: Missing argument for parameter 'completionHandler' in call

        if let placemark = placemarks?[0] as? CLPlacemark {
            let annotation = MKPointAnnotation()
            let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude)
            annotation.coordinate = location
            annotation.title = "\(StudentArray[student].firstName), \(StudentArray[student].lastName)"
            annotation.subtitle = "\(StudentArray[student].grade)"
            self.mapView.addAnnotation(annotation)
        }

    })
4

2 回答 2

2

指定completionHandler参数名称:

geocoder.geocodeAddressString(address, completionHandler: { placemarks, error in
    if let placemark = placemarks.first as? CLPlacemark {
        let annotation = MKPointAnnotation()
        let location = CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude)
        annotation.coordinate = location
        annotation.title = "\(StudentArray[student].firstName), \(StudentArray[student].lastName)"
        annotation.subtitle = "\(StudentArray[student].grade)"
        self.mapView.addAnnotation(annotation)
    }
})

或者使用尾随闭包语法(参见The Swift Programming Language的Closures章节的尾随闭包部分),您可以从and中拉出闭包并将其放在 之后:())

geocoder.geocodeAddressString(address) { placemarks, error in
    if let placemark = placemarks.first as? CLPlacemark {
        let annotation = MKPointAnnotation()
        let location = CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude)
        annotation.coordinate = location
        annotation.title = "\(StudentArray[student].firstName), \(StudentArray[student].lastName)"
        annotation.subtitle = "\(StudentArray[student].grade)"
        self.mapView.addAnnotation(annotation)
    }
}
于 2015-07-23T15:17:02.040 回答
1

在完成处理程序之前添加参数。

geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [AnyObject], error: NSError) -> Void in  // Added argument for parameter 'completionHandler' in call

    if let placemark = placemarks?[0] as? CLPlacemark {
        let annotation = MKPointAnnotation()
        let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude)
        annotation.coordinate = location
        annotation.title = "\(StudentArray[student].firstName), \(StudentArray[student].lastName)"
        annotation.subtitle = "\(StudentArray[student].grade)"
        self.mapView.addAnnotation(annotation)
    }

})
于 2015-07-23T14:47:24.453 回答