Swift UISearchbar how to search a property of a class

Viewed 89

I am trying to implement a UISearchBar using swift, and all of the examples I can find are related to searching an array of strings.

Using a random example, lets say I have a class, called 'Car' with the properties 'manufacturer' and 'model'

I have an array of cars called 'Cars'

I would like to implement a search bar that would filter the results by comparing the string to the 'manufacturer'property in the Cars array.

So far I can hook up everything else regarding the filtered results array, the table view results, etc. The bit I cannot get around is:

  filteredManufacturers = Cars.filter({ (text) -> Bool in
        let tmp: NSString = text as NSString
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)

return range.location != NSNotFound })

The issue I have is I do not know how to reference just a property of a class. If I enter:

filteredManufacturers = Cars.manufacturers.filter....

there is the issue that there is no property called 'manufacturers' for 'Cars' and if. I change it. and try and reference the. class property 'Car.manufacturers' then obviously it doesnt have all. of the actual car data there to filter. Does anybody have any suggestions.

I guess one way is to copy all manufacturers data into an array, and I can search this, but I then have to refer to the. initial indexes to reference their class, and. it seems long wounded.

1 Answers

Firstly, your original approach can be rewritten without using the Objective-C NSString stuff:

filteredManufacturers = Cars.filter {
    $0.lowercased().contains(searchText.lowercased())
}

Searching by manufacturers can be done is a very similar fashion:

filteredManufacturers = Cars.filter {
    $0.manufacturer.lowercased().contains(searchText.lowercased())
}

(Assuming there is a instance property called manufacturer of type String in Car)

Related