let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (Array(MyVariables.dictionary.values) as NSArray).filteredArrayUsingPredicate(searchPredicate)
self.searchArray = array as! [String]
我想以某种方式将字典键附加到过滤后的字典值上?我上面的代码创建了一个新数组,其中仅包含过滤后的值而不是键
最佳答案
你可以避免使用 NSPredicate
并尝试使用 filter
函数,假设你有一个字典 [String:String]
像以下示例中那样声明:
let dict = ["key1": "a", "key2": "ab", "key3": "ac", "hello": "d"]
然后你就可以使用filter
函数,像下面这样使用简短的闭包语法:
// the $0.1 mean the value of the dictionary, if you want to refer to the key you need to use $0.0 instead
var result = dict.filter { $0.1.containsString("a") }
或者只是以更大的方式但在某些方面更易于理解:
var result = dict.filter { (key, value) -> Bool in
return value.containsString("a")
}
以上两段代码返回一个包含字典的键和值的数组:
[("key1", "a"), ("key2", "ab"), ("key3", "ac")]
您只需要使用您的 searchController.searchBar.text!
和您需要的其他东西来调整上面的代码。
希望对你有帮助
关于ios - NSPredicate 通过字典过滤并保留键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34678641/