Search code examples
swiftsearchfilterannotationstitle

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 "[]"


Solution

  • 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 }          // don't remove MKUserLocation
        guard let title = annotation.title else { return false }  // don't remove annotations without any title
        return title != searchString                              // remove those whose title does not match search string
    }
    
    mapView.removeAnnotations(filteredAnnotations)
    

    Obviously, change that != to == as suits your requirements, or whatever, but this illustrates the basic idea of using filter to identify a set of annotations whose title matches some particular criteria.

    For Swift 2, see previous revision of this answer.