为什么我不能返回字典countDict
,如下所示:
我收到错误:
错误:无法转换类型'[(key:String,value: Int)]'返回类型'[String:Int]' return countDict.sorted(by:{$ 0.value> $ 1.value})
码:
let arr = ["red","green","green","black","blue","yellow","red","green","yellow","red","red","green"
,"green","grey","purple","orange","grey","blue","red","red","green","yellow","orange","purple","black","red"
,"blue","green","orange","blue","blue","white","yellow","blue","red","green","orange","purple","blue","black"]
func mostFrequentColor(arr: [String]) -> [String: Int] {
guard arr.count != 0 else {return [:]}
var countDict = [String: Int]()
for color in arr {
countDict[color] = (countDict[color] ?? 0) + 1
}
return countDict.sorted(by: { $0.value > $1.value })
}
print(mostFrequentColor(arr: arr))
答案 0 :(得分:0)
字典按定义未排序,因此Dictionary.sorted(by:)
实际上返回一个元组数组(由Dictionary
中存储的键值对组成,因此错误。如果你密切关注什么是错误说,您会看到您尝试返回的类型为[(key: String, val: Int)]
,这是Array<(String,Int)>
的简写,而不是预期类型[String:Int]
,这是Dictionary<String,Int>
的简写。
您只需删除排序即可解决错误。如果您确实需要对颜色进行排序,则需要使用其他数据结构,因为Dictionary
按定义未排序。
您也不需要guard
声明,因为您无论如何都要将countDict
设为空Dictionary
,而for ... in
循环只是赢得了arr
。如果func mostFrequentColor(arr: [String]) -> [String: Int] {
var countDict = [String: Int]()
for color in arr {
countDict[color, default: 0] += 1
}
return countDict
}
没有元素,则执行t。修改Dictionary的值时,也可以使用简写语法。
func mostFrequentColor(arr: [String]) -> [String: Int] {
return colors.reduce(into: [String:Int](), { accumulatedResult, currentColor in
accumulatedResult[currentColor, default: 0] += 1
})
}
mostFrequentColor(arr: colorsArray) //["red": 8, "blue": 7, "grey": 2, "white": 1, "green": 8, "black": 3, "orange": 4, "purple": 3, "yellow": 4]
使用更实用的方法,您的功能实际上可以缩短为:
<form method="POST" action="/">
<input type="submit" name="Click">