JVS JVS - 1 year ago 108
Swift Question

Filtering Array but keeping the indexPath position

I am using a

in my

I am filtering an array of usernames with a

self.filteredChats.removeAll(keepCapacity: false)

let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (self.gruppenNamen as NSArray).filteredArrayUsingPredicate(searchPredicate)
self.filteredChats = array as! [String]

Is there a way to store the indexPath of each filtered element?
I need to know that in order to display my cells correctly, since I am also using arrays for images and other data.

Answer Source

Let's says that you have gruppenNamen and gruppenImages. You want to keep them synchronized. I would strongly suggest that you create a custom class with a property name, and a property image.

Since you seem to not want that, you could use indexesOfObjectsPassingTest: and objectsAtIndexes:. I don't use Swift, so I'll code in Objective-C, but it should be easily translated.

NSIndexSet *indexes = [self.gruppenNamen indexesOfObjectsPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [(NSString *)obj rangeOfString:searchController.searchBar.text options:NSCaseInsensitiveSearch].location != NSNotFound;
self.filteredChat = [self. gruppenNamen objectsAtIndexes:indexes];
self.filteredImages = [self.gruppenImages objectsAtIndexes:indexes];

I used rangeOfString:options for the equivalent of contains[c] of your predicate. You could use a NSPredicate here too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download