我使用key
从字典中获取reduce
,例如执行以下操作:
let namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]
let namesString = namesAndScores.reduce("",
combine: { $0 + "\($1.0), " })
print(namesString)
但我想知道如何使用value
从dictionary
获取reduce
?
任何帮助将不胜感激。 感谢。
答案 0 :(得分:2)
我建议你一个更简单的方法
let names = namesAndScores.keys.joinWithSeparator(", ")
// Brian, Anna, Craig, Donna
let values = namesAndScores.values.map(String.init).joinWithSeparator(", ")
// 2, 2, 8, 6
let values = String(namesAndScores.values.reduce("") { "\($0), \($1)"}.characters.dropFirst(2))
// 2, 2, 8, 6
答案 1 :(得分:2)
let dict = ["John":"","Donna":""]
let str = dict.reduce("") {
return $0 + "\($1.key) likes the color: \($1.value) "
}
Swift.print(str)//Donna likes the color: John likes the color: