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.
The
annotations
property ofMKMapView
returns[AnyObject]!
andAnyObject
does not have acoordinate
property. You have to cast to an[MKAnnotation]
array:(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: