谁能告诉我为什么我的过滤数组是空的?
问题描述:
我有一个表格视图和一个搜索栏(编程)。我想显示过滤结果,所以我创建了一个数组(称为:todoTitle),其中包含我的待办事项活动的标题(我有一个单独的对象,其中一个属性是标题)。我使用updateSearchResults方法,并在其中使用过滤器方法返回正确的待办事项。为了检查数组是否为空,我在该函数内部编写代码以在每个数组内部打印待办事项。这里是我的代码updateSearchResults内(对于:)功能谁能告诉我为什么我的过滤数组是空的?
//filtering through todos' titles
filteredTodos = self.todosTitle.filter({ (title: String) -> Bool in
if title.lowercased().contains((self.searchController.searchBar.text?.lowercased())!) {
return true
} else {
print ("S \(todosTitle)")
print ("t \(title)")
print (filteredTodos)
return false
}
})
//updating the results TableView
self.resultsController.tableView.reloadData()
}
``
todosTitle数组不为空,所以我不明白为什么我的filteredTodos是空的。有没有人有任何想法,为什么会发生?
答
您只需要检查待办事项项目标题是否包含搜索文本。这里有一个简单的例子,我用一个字符串数组和一个搜索文本字符串进行了测试。也许,分离出你的搜索文本的分配,以确保您从searchBar.text
let todosTitle = ["One", "Two", "Three"]
let searchText = "t"
//filtering through todos' titles
let filteredTodos = todosTitle.filter({ (title: String) -> Bool in
return title.lowercased().contains(searchText.lowercased())
})
print(filteredTodos) //["Two", "Three"]
得到你所期望的字符串打印关闭*内部结果数组'filteredTodos' *没有太大的意义。 –
你应该打印self.searchController.searchBar.text?控制和检查。它会阻止,这可能是原因。 – adev
在过滤器返回之前,'filteredTodos'不会被设置为过滤器的结果。只是为了清楚 – PeejWeej