我在 Swift中有一个对象,它是Dictionary String,String []类型的字典.我希望能够在维护字典结构的同时过滤String []数组. let list: DictionaryString, String[] = [ "Vegetables" : [ "Carrot", "Potato" ], "Fruit" : [
let list: Dictionary<String, String[]> = [ "Vegetables" : [ "Carrot", "Potato" ], "Fruit" : [ "Apple", "Orange", "Banana" ] ]
我希望能够过滤包含“O”的所有内容,并最终得到如下所示的内容:
[ "Vegetables" : [ "Carrot", "Potato" ], "Fruit" : [ "Orange" ] ]
要过滤数组,我一直这样做:
["Carrot", "Potato"].filter { ($0 as NSString).containsString("o") }
但是,我现在正在努力的部分是映射到字典 – 因为那时我可以保留密钥并在值上调用该过滤器函数.我该怎么做呢?提前致谢!
您可以在for循环中执行此操作:for (key, array) in list { list[key] = array.filter { ($0 as NSString).containsString("o") } }
您还可以将自己的地图方法添加到词典:
extension Dictionary { func map(f: (KeyType, ValueType) -> ValueType) -> [KeyType:ValueType] { var ret = [KeyType:ValueType]() for (key, value) in self { ret[key] = f(key, value) } return ret } }
然后你可以简单地做:
var filteredList = list.map { $1.filter { ($0 as NSString).containsString("o") } }
注意:我在Dictionary上的map实现返回字典的副本,更像是Array的map方法