How to use UISearchBarController with array subsection

爷,独闯天下 提交于 2019-12-25 09:50:36

问题


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?


回答1:


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: [""])]



来源:https://stackoverflow.com/questions/46945634/how-to-use-uisearchbarcontroller-with-array-subsection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!