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?
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.
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With