Search code examples
arraysswiftstructfilteruisearchcontroller

Filter a struct array according to a NSPredicate SWIFT


I have an UITableView and an UISearchController. I want to filter my array of data (named: allGames) according to the NSPredicate of the UISearchBar.text.

My code only filter an array of string like this:

func updateSearchResults(for searchController: UISearchController) {

    filteredGames.removeAll(keepingCapacity: false)

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    let array = (allGames).filtered(using: searchPredicate)

    filteredGames = array as! [String]

    self.tableView.reloadData()
}

Here I can filter my array. But if I create this struct:

struct Games {

    var name: String?
    var type: String?
    var image: UIImage?
}

How can I filter the array according to the game names and types? Thanks in advance for your help.


Solution

  • Assuming allGames is an array [Games] – by the way the struct is supposed to be named in singular form Game – I highly recommend to use the native Swift filter function

    let searchText = searchController.searchBar.text!
    let fileredGames = allGames.filter { $0.name?.range(of: searchText, options: [.caseInsensitive]) != nil 
                                      || $0.type?.range(of: searchText, options: [.caseInsensitive]) != nil }
    

    Consider also to declare type and name in the struct as non-optional.