theslash
theslash

Reputation: 99

Swift Dictionary with Array of Strings remove Value

So, I have a Dictionary that contains an Array of Strings like this:

var dict = ["Section1": ["dev1", "dev2"], "Section2": ["dev3", "dev4"]]

And now I have to be able to remove a value from the array. Example: I want to remove "dev4" no matter if its in "Section1" or "Section2".

How would I be doing this?

Upvotes: 0

Views: 1919

Answers (4)

Abizern
Abizern

Reputation: 150605

With Swift4 there is an option to apply a map to the values of a dictionary:

var dict = ["Section1": ["dev1", "dev2"], "Section2": ["dev3", "dev4"]]
dict = dict.mapValues{ $0.filter{ $0 != "dev4" } }

which gives the result:

dict // -> ["Section1": ["dev1", "dev2"], "Section2": ["dev3"]]

Upvotes: 3

TMob
TMob

Reputation: 1278

for key in dict.keys {
    dict[key] = dict[key]!.filter({ $0 != "dev4"})
}

Upvotes: 1

pacification
pacification

Reputation: 6018

Mini version:

dict.forEach({ (k, v) in dict[k] = v.filter({ $0 != "dev4" }) })
print(dict) // ["Section1": ["dev1", "dev2"], "Section2": ["dev3"]]

Upvotes: 0

Vinod Vishwanath
Vinod Vishwanath

Reputation: 5891

Some sample code:

func removeValue(value: String, fromDict dict: [String: [String]]) -> [String: [String]] {
    var out = [String: [String]]()
    for entry in dict {
        out[entry.key] = entry.value.filter({
            $0 != value
        })
    }
    return out
}

var dict = ["Section1": ["dev1", "dev2"], "Section2": ["dev3", "dev4"]]
let new = removeValue(value: "dev4", fromDict: dict)

Upvotes: 0

Related Questions