gpt4 book ai didi

swift - 字符串编译错误中最常出现的名称

转载 作者:搜寻专家 更新时间:2023-11-01 06:13:15 25 4
gpt4 key购买 nike

我正在编写一个函数,它返回一个字典,其中包含出现次数最多的名称作为 key,出现次数作为 value,但是,我得到了一个错误 - 请参阅下面的代码:

let names = ["Adam", "Bob", "Charlie", "Dylan", "Edward"]    

func getMostCommonName(array: [String]) -> [String: Int] {

var namesDictionary: [String: Int] = [:] // holds all the names and their occurrences
var mostCommonNames: [String: Int] = [:] // will hold the most common name(s) and their occurrences

for name in array {
if let count = namesDictionary[name] {
namesDictionary[name] = count + 1
}
else {
namesDictionary[name] = 1
}
}

let highestOccurence = namesDictionary.values.max()

for name in namesDictionary {
if namesDictionary[name] == highestOccurence {
mostCommonNames[name] = highestOccurence // throws an error
}
}

return mostCommonNames
}

getMostCommonName(array: names)

错误是无法使用类型为“(key: String, value: Int)”的索引下标类型为“[String : Int]”的值。我真的不明白为什么会抛出这个错误。有没有人要?

最佳答案

因为name是(key: String, value: Int)的类型,是元组类型,可以这样访问key和value

for element in namesDictionary {
if element.value == highestOccurence {
mostCommonNames[element.key] = highestOccurence
}
}

此外,我建议像这样编写for in

for (key,value) in namesDictionary {
if value == highestOccurence {
mostCommonNames[key] = highestOccurence
}
}

有关元组类型的更多信息:document

关于swift - 字符串编译错误中最常出现的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50691957/

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