3

I have created an searchController and therefor i'm trying t make it filter content according to the text in the UISearchController. I've created a custom Object looking like below. I've tried using NSPredicate, but keep getting:

cannot convert value of type NSPredicate to expected type @noescape (organization) throws...

class Organization: Object {
    var id: Int = 0
    var name: String = ""
    var shortName: String = ""
    var image: NSData = NSData()
    var pinImage: NSData = NSData()
    let locations = List<Location>()

}

Then I have an array called sortedLocations in my ViewController which contains a number of Organization Objects.

What I've tried so far:

func updateSearchResultsForSearchController(searchController: UISearchController)
{
    filteredTableData.removeAll(keepCapacity: false)

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

    let array = sortedLocations.filter(searchPredicate)
    filteredTableData = array as! [Organization]



    self.tableView.reloadData()
}

1 Answer 1

5

The filter() method of SequenceType does not take an NSPredicate as an argument, but a closure, e.g.

let filteredTableData = sortedLocations.filter {
    $0.name.localizedCaseInsensitiveContainsString(searchText)
}

The closure is called for each array element (here using the shorthand argument $0) and returns true or false to indicate if the element is to be included in the filtered result or not.


You can use an NSPredicate to filter an NSArray, that would look like

let filtered = someNSArray.filteredArrayUsingPredicate(predicate)

but there is no reason to use this if you have a Swift array.

Sign up to request clarification or add additional context in comments.

4 Comments

hmm but filteredTableData, doesnt seem to contain anything when i write something which is contain in an object name? Do i need to append anything?
@PeterPik: I have just double-checked it with a small test program and it worked as expected.
but shouldnt i append anything aswell?
@PeterPik: Sorry, I don't understand. Append what? sortedLocations is the "full" array with all organizations and filteredTableData is the filtered array with organizations whose name contains the given search string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.