如何将 UISearchBarController 与数组子部分一起使用

How to use UISearchBarController with array subsection

我正在使用以下数组结构来创建包含部分的 tableView

struct words {

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

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

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

我想使用一个使用类似代码的搜索控制器

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 { [=11=].coptic.lowercased().contains(searchController.searchBar.text!.lowercased()) }

    }

不幸的是,因为科普特语是一个 [字符串],而不仅仅是一个字符串,所以代码不起作用。有没有办法修改它以便能够过滤对科普特小节的搜索?

你可以这样做。

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

搜索 "app"

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