Search code examples
arraysswifttableviewuisearchbarsub-array

How to use UISearchBarController with array subsection


I am using the following array structure to create a tableView with sections

struct words {

    var sectionName : String!
    var coptic : [String]!
    var english : [String]!
}

var array = [words]()
var filtered = [words]()

array = [words(sectionName: "", coptic: [""], English: [""])]

I want to utilize a searchcontroller using similar code to this

func updateSearchResults(for searchController: UISearchController) {
    // If we haven't typed anything into the search bar then do not filter the results
    if searchController.searchBar.text! == "" {
        filtered = array
    } else {
        // Filter the results
        filtered = array.filter { $0.coptic.lowercased().contains(searchController.searchBar.text!.lowercased()) }

    }

Unfortunately, because coptic is a [String], and not simply a String, the code doesn't work. Is there a way to modify this to be able to filter a search for the coptic subsection?


Solution

  • you can do like this.

    func updateSearchResults(for searchController: UISearchController) {
        // If we haven't typed anything into the search bar then do not filter the results
        if searchController.searchBar.text! == "" 
        {
            filtered = array
        }
        else 
        {
            filtered.removeAll()
            array.forEach({ (word:words) in
    
                var tempWord:words = words.init(sectionName: word.sectionName, coptic: [""], english: [""])
                let copticArray = word.coptic.filter({ (subItem:String) -> Bool in
                        let a = subItem.lowercased().contains(searchController.searchBar.text!.lowercased())
                        return a;
                    })
                tempWord.coptic = copticArray
                filtered.append(tempWord)
            })
    
       }
    }
    

    Input array = array = [words(sectionName: "abc", coptic: ["apple","ball","cat","dog"], english: [""])]

    Search For "app"

    OUTPUT words(sectionName: abc, coptic: ["apple"], english: [""])]