在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]