Search code examples
swiftuisearchbaruisearchcontrollerobjectmapper

how to filter data from object mapper class


i want to implement search functionality in my app but i get data from services. i have an array like this in object mapper

class Country : Mappable {

var countryName:String = ""
var countryID:Int = 0
var countryImage:String = ""
var countryColor:String = ""

required init?(_ map: Map) {

}
func mapping(map: Map) {

    countryID           <- map["id"]
    countryName         <- map["name"]
    countryColor        <- map["color"]
    countryImage        <- map["image"]
}
}

from here i want to filter my data for search functionality how to do this.

here i am filtering only country names but i want to filter whole array how i can do that

func updateSearchResultsForSearchController(searchController: UISearchController) {

    self.filteredData = self.countryNames.filter { (country:String) -> Bool in
        if country.lowercaseString.containsString(self.searchController.searchBar.text!.lowercaseString) {
            return true
        } else {
            return false
        }
    }
    print(filteredData)
    // update results table view

    self.resultController.tableView.reloadData()
}

Solution

  • You can filter your array like this way.

    let filter = countries.filter { $0.countryName.lowercaseString.containsString(self.searchCon‌​troller.searchBar.te‌​xt!.lowercaseString) }
    self.resultController.tableView.reloadData()