问题
I'm trying to iterate through an array of annotations by getting by self.mapView.annotations
.
The issue I'm having is that i'm getting an error because Coordinate is unavailable: APIs deprecated as of iOS 7 and earlier are unavailable to Swift.
Any ideas how I can fix this? I have a look at the iOS developer library but I couldn't find any way of getting the coordinate for each annotation.
var zoomRect:MKMapRect = MKMapRectNull;
for (index,annotation) in enumerate(self.mapView.annotations) {
var annotationPoint:MKMapPoint = MKMapPointForCoordinate(annotation.coordinate)
var pointRect:MKMapRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
self.mapView.setVisibleMapRect(zoomRect, animated: true)
The main idea for this code is to center the map so that users will be able to see all the annotations. I got this code in Objective C (another question from SO) and converted it to Swift but still having no luck.
回答1:
The annotations
property of MKMapView
returns [AnyObject]!
and AnyObject
does not have a coordinate
property.
You have to cast to an [MKAnnotation]
array:
var zoomRect = MKMapRectNull
for annotation in self.mapView.annotations as [MKAnnotation] {
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1)
zoomRect = MKMapRectUnion(zoomRect, pointRect)
}
(The explicit type annotation in your code are not necessary, and the variables
inside the loop are in fact constants, so you can declare them with let
.)
Note that you could replace the for-loop by a reduce operation:
let zoomRect = reduce(self.mapView.annotations as [MKAnnotation], MKMapRectNull) {
rect, annotation in
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1)
return MKMapRectUnion(rect, pointRect)
}
来源:https://stackoverflow.com/questions/27195494/swift-coordinate-is-unavailable-apis-deprecated-as-of-ios-7