5

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.

1
  • 2
    In combine: { $0 + "\($1.0), " }), you use $1.0 to get the key from the dictionary, you also can use$1.1 to get the value. Is this you want? Commented Aug 8, 2016 at 23:46

2 Answers 2

5

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: 🔵 
Sign up to request clarification or add additional context in comments.

Comments

2

I'll suggest you an easier way

let names = namesAndScores.keys.joinWithSeparator(", ")
//  Brian, Anna, Craig, Donna

let values = namesAndScores.values.map(String.init).joinWithSeparator(", ")
// 2, 2, 8, 6

Update: code for reduce

 let values = String(namesAndScores.values.reduce("") { "\($0), \($1)"}.characters.dropFirst(2))
// 2, 2, 8, 6

3 Comments

Thanks, But I know the way you mentioned.
@AK1: Ok I will add the code for reduce then. One question: Why using reduce when there is an easier way?
That would be helpful. Nothing much learning swift and wanted to know how to do things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.