通过执行以下操作,我key使用reducelike从字典中获取了 :
let namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]
let namesString = namesAndScores.reduce("",
combine: { $0 + "\($1.0), " })
print(namesString)
Run Code Online (Sandbox Code Playgroud)
但我想知道如何value从dictionary使用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:
Run Code Online (Sandbox Code Playgroud)
我会建议你一个更简单的方法
let names = namesAndScores.keys.joinWithSeparator(", ")
// Brian, Anna, Craig, Donna
let values = namesAndScores.values.map(String.init).joinWithSeparator(", ")
// 2, 2, 8, 6
Run Code Online (Sandbox Code Playgroud)
let values = String(namesAndScores.values.reduce("") { "\($0), \($1)"}.characters.dropFirst(2))
// 2, 2, 8, 6
Run Code Online (Sandbox Code Playgroud)