Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access values in a dictionary using reduce in swift?

Tags:

swift

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.

like image 451
Abhinay Reddy Keesara Avatar asked Aug 08 '16 23:08

Abhinay Reddy Keesara


People also ask

How do you check if a value is in a dictionary Swift?

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.

Which method is used to update value for a particular key in a dictionary in Swift?

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.

Are dictionary values optional Swift?

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 .


1 Answers

Accessing Value and Key w/ reduce 👌

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: 🔵 
like image 56
Sentry.co Avatar answered Nov 15 '22 07:11

Sentry.co