Filter nested lists inside a dictionary in Swift

I have an object in Swift, which is a type dictionary Dictionary<String, String[]>. I would like to be able to filter an array String[]while maintaining a dictionary structure.

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

I would like to be able to filter everything that contains "O", and in the end I get something similar to this:

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

To filter arrays, I did this:

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

However, the part that I am currently facing is matching through a dictionary, because then I can save the key and call this filter function for the value. How should I do it? Thanks in advance!

+4
source share
2 answers

You can do this in a loop for in:

for (key, array) in list {
    list[key] = array.filter { ($0 as NSString).containsString("o") }
}

You can also add your own map method to the dictionary:

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

: map Dictionary , map Array

+5

1 . const, . :

//it 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
    );
}
0

Source: https://habr.com/ru/post/1543686/


All Articles