gpt4 book ai didi

swift - 使用 [String : Int] in Swift 类型的简写] 返回字典

转载 作者:行者123 更新时间:2023-11-30 11:49:25 24 4
gpt4 key购买 nike

为什么我不能返回如图所示的字典countDict:

我收到错误:

error: cannot convert return expression of type '[(key: String, value: Int)]' to return type '[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))

最佳答案

字典根据定义是未排序的,因此Dictionary.sorted(by:)实际上返回一个元组数组(由存储在 Dictionary 中的键值对组成,因此会出现错误。如果您密切注意错误的内容,您会发现您尝试返回的类型是[(key: String, val: Int)] ,它是 Array<(String,Int)> 的简写,而不是预期类型 [String:Int] ,它是 Dictionary<String,Int> 的简写。

只需删除排序即可解决该错误。如果您确实需要对颜色进行排序,则需要使用另一个数据结构,因为 Dictionary根据定义未排序。

您也不需要 guard声明,因为您正在创建 countDict作为一个空Dictionary不管怎样,for ... in循环根本不会执行 if arr没有元素。修改字典的值时,您还可以使用简写语法。

func mostFrequentColor(arr: [String]) -> [String: Int] {
var countDict = [String: Int]()
for color in arr {
countDict[color, default: 0] += 1
}
return countDict
}

使用更实用的方法,您的函数实际上可以缩短为:

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]

关于swift - 使用 [String : Int] in Swift 类型的简写] 返回字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48493698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com