的UISearchBar不是在阵列

问题描述:

与子部分的工作,我使用所谓的部分数组变量作为表视图具有可折叠部分:的UISearchBar不是在阵列

var sections = [ 

     // TESTING CODE FOR SECTIONS 
     Section(sec: "One", 
       subSec: ["A", "B", "C", "D", "E"], 
       expanded: false), 

     Section(sec: "Two", 
       subSec: ["A", "B", "C", "D", "E"], 
       expanded: false), 

     Section(sec: "Three", 
       subSec: ["A", "B", "C", "D", "E"], 
       expanded: false), 

我试图用UISearchController使表视图搜索。以下是我迄今为止尝试,但它不工作:

func filterContentForSearchText(_ searchText: String, scope: String = "All") { 
    filtered = sections.filter({(section : Section) -> Bool in 
    return section.subSec.name.lowercased().contains(searchText.lowercased()) 
    }) 

    tableView.reloadData() 
} 

我了解功能的作品,但似乎无法得到它与我的subSec中的变量。

//SEARCH 
    var filteredSections: [String]? 
    let searchController = UISearchController(searchResultsController: nil) 


    override func viewDidLoad() { 
     super.viewDidLoad() 

     //SEARCH 
     filteredSections = sections 
     searchController.searchResultsUpdater = self 
     searchController.hidesNavigationBarDuringPresentation = false 
     searchController.dimsBackgroundDuringPresentation = false 
     tableView.tableHeaderView = searchController.searchBar 

    } 

我收到错误,如'不能分配类型'[Section]'的值来键入'[String]?'我明白为什么,但我不知道如何解决这个问题。

段定义:

struct Section { 
    var sec: String! 
    var subSec: [String]! // [ ] = Array of Strings 
    var expanded: Bool! 

    init(sec: String, subSec: [String], expanded: Bool) { 
     self.sec = sec 
     self.subSec = subSec 
     self.expanded = expanded 
    } 
} 
+0

你究竟想要返回什么? 'filteredSections'是一个字符串数组,而'sections'是一个'Sections'数组,所以'filteredSections = sections'显然不起作用。你想返回一个数组或字符串? –

+0

我希望能够返回subSec的名称,如果他们匹配搜索字符串。即如果用户在搜索字段中键入'A',则它只会在tableView中显示'A'。它与一个正常的字符串数组一起工作,但不是我使用sections变量的方式。 – 128K

filteredSections是一个字符串数组,你要转让叫Section s,这回的Section秒的阵列阵列中的过滤器功能的输出,所以它显然是行不通的。

如果你想返回String S作为过滤的Section在数组的结果,你需要结合filtermap,它可以用一个flatMap来完成。

的flatMap内三元运算符检查作为过滤器做了同样的情况,但如果条件计算结果为真,nil否则,该flatMap简单地忽略,因此输出数组将只包含匹配小节名返回section.subSec.name

func filterContentForSearchText(_ searchText: String, scope: String = "All") { 
    filtered = sections.flatMap{ return $0.subSec.name.lowercased().contains(searchText.lowercased()) ? searchText : nil } 

    tableView.reloadData() 
} 

既然你没有包括在代码中的Section定义,我无法测试的功能,但如果subSec.nameString,它会工作得很好。

+0

感谢您的帮助! subSec.name是不可能的,因为subSec没有成员'name' – 128K

+0

到你的'tableView'被定义的视图控制器。 –

+0

Btw哪里是'subSec.name'来自你的代码,它没有在任何地方定义? –