J.Doe
J.Doe

Reputation: 725

Update all values of a Dictionary

I have a dictionary with this structure

var profiles: Dictionary<String, Bool> = ["open": true, "encrypted": false, "sound":true, "picture":false]

I want to create a function that reset all the dictionary values to true. Is there a short method to do that or shall I loop through it and change the values one by one?

Upvotes: 5

Views: 6627

Answers (3)

JAL
JAL

Reputation: 42489

Easy one-liner for you:

profiles.keys.forEach { profiles[$0] = true }

This iterates through every key in the dictionary and sets the value for that key to true. $0 represents the first argument in the forEach closure (the key). I don't see a way to change all of the values to a single value without looping.

Upvotes: 20

Adolfo
Adolfo

Reputation: 1862

dictionary.forEach({ (key, value) -> Void in 
    dictionary[key] = true                 
})

And here another approach. In this case only update these dictionary entries which must be updated..

dictionary.filter({ $0.value == false })
    .forEach({ (key, _) -> Void in 
              dictionary[key] = true               
})

Upvotes: 3

Ashley Mills
Ashley Mills

Reputation: 53231

There are many ways to skin this particular cat…

profiles.forEach { profiles[$0.0] = true }

Upvotes: 1

Related Questions