在Swift中过滤字典中的嵌套列表

时间:2014-06-07 15:56:30

标签: swift

我在Swift中有一个对象Dictionary<String, String[]>的字典。我希望能够在保持字典结构的同时过滤String[]数组。

let list: Dictionary<String, String[]> = [
    "Vegetables" : [ "Carrot", "Potato" ],
    "Fruit" : [ "Apple", "Orange", "Banana" ]
]

我希望能够过滤包含&#34; O&#34;的所有内容,并最终得到如下内容:

[
    "Vegetables" : [ "Carrot", "Potato" ],
    "Fruit" : [ "Orange" ]
]

要过滤数组,我一直这样做:

["Carrot", "Potato"].filter { ($0 as NSString).containsString("o") }

然而,我现在正在努力的部分是映射字典 - 因为那时我可以保留密钥并在值上调用该过滤器函数。我该怎么做呢?提前谢谢!

2 个答案:

答案 0 :(得分:5)

您可以在for in循环中执行此操作:

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") } }

注意:我在mapDictionary的实现会返回字典的副本,使其更像map的{​​{1}}方法< / p>

答案 1 :(得分:0)

你可以枚举它并过滤1次。我只是列出了一个变量而不是一个const来使它更​​简单。这是代码:

//it's a variable
var list: Dictionary<String, String[]> = [
    "Vegetables" : [ "Carrot", "Potato" ],
    "Fruit" : [ "Apple", "Orange", "Banana" ]
]


for (key, array) in list {
    list[key] = array.filter({
        (x : String) -> Bool in
        return !(x.rangeOfString("o", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil).isEmpty)
        })
}
NSLog("%@", list)

输出将是:

{
    Fruit =     (
        Orange
    );
    Vegetables =     (
        Carrot,
        Potato
    );
}