How do I remove all map annotations in swift 2 How do I remove all map annotations in swift 2 xcode xcode

How do I remove all map annotations in swift 2


In Swift 2 annotations is declared as non optional array [MKAnnotation] so you can easily write

let allAnnotations = self.mapView.annotationsself.mapView.removeAnnotations(allAnnotations)

without any type casting.


self.mapView.removeAnnotations(self.mapView.annotations)

If you don't want remove user location.

self.mapView.annotations.forEach {  if !($0 is MKUserLocation) {    self.mapView.removeAnnotation($0)  }}

Note: Objective-C now have generics, it is no longer necessary cast the elements of 'annotations' array.


SWIFT 5

If you don't want to remove user location mark:

let annotations = mapView.annotations.filter({ !($0 is MKUserLocation) })mapView.removeAnnotations(annotations)