字符串中最常见的名称编译错误

时间:2018-06-05 04:17:27

标签: swift

我正在编写一个函数,它返回一个字典,其中包含最多出现的名称为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)

错误为Cannot subscript a value of type '[String : Int]' with an index of type '(key: String, value: Int)'。我真的不明白为什么会抛出这个错误。任何人?

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

你也可以试试这个:

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