在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) 将奇数整数除以2而不是错误的计算时,看到错误不是更好吗?
Ruby中的示例(我猜它在其他语言中是相同的,因为整数和浮点数是常见的数据类型):
39 / 2 => 19
我得到的输出不是19.5,因为我们要求整数的值除以整数,而不是浮点数(39.0)除以整数.我的问题是,如果这些数据类型的限制阻止它计算正确的值,为什么输出最不正确的值?