I got the key
from the dictionary using reduce
like by doing the following:
let namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]
let namesString = namesAndScores.reduce("",
combine: { $0 + "\($1.0), " })
print(namesString)
But I would like to know how to get the value
from the dictionary
using the reduce
?.
Any help would be appreciated. Thanks.
Swift – Check if Specific Key is Present in Dictionary To check if a specific key is present in a Swift dictionary, check if the corresponding value is nil or not. If myDictionary[key] != nil returns true, the key is present in this dictionary, else the key is not there.
To change the value of a key-value pair, use the . updateValue() method or subscript syntax by appending brackets [ ] with an existing key inside them to a dictionary's name and then adding an assignment operator ( = ) followed by the modified value.
Dictionary accessor returns optional of its value type because it does not "know" run-time whether certain key is there in the dictionary or not. If it's present, then the associated value is returned, but if it's not then you get nil .
let dict = ["John": "🔵", "Donna": "🔴"]
let str = dict.reduce("") {
$0 + "\($1.key) likes the color: \($1.value) "
}
print(str) // Donna likes the color: 🔴 John likes the color: 🔵
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