1

I've the following array of objects which I'm trying to filter and return for a searchDosplayController.

var family = [Family]()// fetchedFamily
var filteredFamily: [Family]! // filter fetched events

And that is how, I'm filtering it:

func updateSearchResultsForSearchController(searchController: UISearchController) {
        let searchText = searchController.searchBar.text

        self.filteredProvince = provinces
                if !searchText.isEmpty {
                    let searchPredicate = NSPredicate(format: "name CONTAINS[c] %@", searchText)
                    let array = (filteredProvince as NSArray).filteredArrayUsingPredicate(searchPredicate)
                    filteredProvince = array as! [Province]
}

However nothing is getting returned when I'm searching. And I tried to do it in this way:

filteredFamily = searchText.isEmpty ? family : family.filter({(dataString: String) -> Bool in
           return dataString.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil
        })

But, I'm receiving the following error: 'Family is not a subtype of String'. Is there any better way to filter the Family? Because, the filtered result has to be sent back to searchDisplayController.

Thanks in advance.

1 Answer 1

1

So we have a Family class that does look like this right?

class Family {
    let name : String
    init(name:String) {
        self.name = name
    }
}

Then we have a list of families:

var families = [Family]()

And we want to extract all the families where the name property contains a given text.

let searchText = "something here"

Good, first of all we add this extension to the String struct.

extension String {
    func contains(find: String) -> Bool {
        return self.rangeOfString(find) != nil
    }
}

And finally we can filter the families writing:

let filtered = families.filter { $0.name.contains(searchText) }

Hope this helps.

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

2 Comments

thanks for the attempt but didn't work. The family class is an object of the coredata
When searching in the searchDisplayController, only one result got displayed over and over

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.