本文介绍了在Swift中过滤字典数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有字典的数组示例:
I have An Array With Dictionaries example :
(
{
Email = "[email protected]";
Name = "Kate Bell";
Number = "(555) 564-8583";
},
{
Email = "[email protected]";
Name = "Daniel Higgins";
Number = "555-478-7672";
}
)
我想根据键名称"过滤该词典
And i want to filter this dictionary according to Key "Name"
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let predicate = NSPredicate(format:"Name == %@", searchText)
let filteredArray = (arrContact as NSMutableArray).filteredArrayUsingPredicate(predicate)
print(filteredArray)
if(filteredArray.count == 0){
searchActive = false;
} else {
searchActive = true;
}
tblData.reloadData()
}
我总是从上述快速代码得到空数组的结果.请帮助我解决此问题.谢谢
I am always getting empty array in result from above swift code. Please help me to resolve this issue. Thanks
推荐答案
我建议改用Swift的filter
:
I suggest using Swift's filter
instead:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let filteredArray = arrContact.filter { $0["Name"] == searchText }
print(filteredArray)
if filteredArray.isEmpty {
searchActive = false
} else {
searchActive = true
}
tblData.reloadData()
}
正如@LeoDabus在他的评论中提到的,您甚至可以进一步简化:
And as mentioned by @LeoDabus in his comment, you can even simplify further:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let filteredArray = arrContact.filter { $0["Name"] == searchText }
print(filteredArray)
searchActive = !filteredArray.isEmpty
tblData.reloadData()
}
这篇关于在Swift中过滤字典数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!