在
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]
你的方法非常可靠,但这会带来一些改进.我使用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 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。