Swift中的字数统计

mml*_*mla 6 algorithm swift

在Swift中编写简单的字数统计函数有什么更优雅的方法?

//Returns a dictionary of words and frequency they occur in the string
func wordCount(s: String) -> Dictionary<String, Int> {
    var words = s.componentsSeparatedByString(" ")
    var wordDictionary = Dictionary<String, Int>()
    for word in words {
        if wordDictionary[word] == nil {
            wordDictionary[word] = 1
        } else {
            wordDictionary.updateValue(wordDictionary[word]! + 1, forKey: word)
        }
    }
    return wordDictionary
}

wordCount("foo foo foo bar")
// Returns => ["foo": 3, "bar": 1]
Run Code Online (Sandbox Code Playgroud)

Das*_*ash 8

你的方法非常可靠,但这会带来一些改进.我使用Swifts"if let"关键字存储值计数以检查可选值.然后我可以在更新字典时使用count.我使用updateValue的简写表示法(dict [key] = val).我还在所有空格上分割原始字符串,而不是仅仅一个空格.

func wordCount(s: String) -> Dictionary<String, Int> {
    var words = s.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    var wordDictionary = Dictionary<String, Int>()
    for word in words {
        if let count = wordDictionary[word] {
            wordDictionary[word] = count + 1
        } else {
            wordDictionary[word] = 1
        }
    }
    return wordDictionary
}
Run Code Online (Sandbox Code Playgroud)