Cory Billeaud Cory Billeaud - 25 days ago 16
Swift Question

Remove annotations containing a title equal/not equal to a String?

I have looked for a couple of days on trying to remove annotations that a title equal or not equal to a string that is selected from a uicollection View cell didSelect from another view controller. I get the string passed to my view controller that contains my mapview. I use a custom annotation that is the model for how the annotations are displayed.

How do I select and remove the custom annotations by their title. I already have an array of dictionaries that contains the data the annotations will use once the other annotations are removed. I know how to remove ALL the annotations, but not how to just remove the ones that have titles that are equal/not equal to the search string.

Why is nothing on the web or current for swift 3 for such a function?

I have come up with this, but only removed annotations and does display the "filteredAnnotations"

var filteredAnnotations = self.mapview.annotations.filter {($0.title != nil) && isEqual(searchString) }

print(filteredAnnotations)

self.mapview.removeAnnotations(self.mapview.annotations)
self.mapview.addAnnotations(filteredAnnotations)


using the print statement only returns an empty array of "[]"

Rob Rob
Answer

Use filter to get a list of all annotations that should be removed (i.e. whose title is not your search string, but isn't a MKUserLocation, either) and then remove them.

In Swift 3:

let filteredAnnotations = mapView.annotations.filter { annotation in
    if annotation is MKUserLocation { return false }

    if let title = annotation.title, title != searchString {
        return true
    }
    return false
}
mapView.removeAnnotations(filteredAnnotations)

In Swift 2.3:

let filteredAnnotations = mapView.annotations.filter { annotation in
    if annotation is MKUserLocation { return false }

    if let title = annotation.title where title != searchString {
        return true
    }
    return false
}
mapView.removeAnnotations(filteredAnnotations)