Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
J.Doe Avatar asked Dec 02 '22 13:12

J.Doe


2 Answers

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.

like image 171
JAL Avatar answered Jan 04 '23 22:01

JAL


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               
})
like image 31
Adolfo Avatar answered Jan 05 '23 00:01

Adolfo