我正在尝试探索 Swift 编程语言。我在搜索 Swift API 时找到了 UIReferenceLibraryViewController
类。我找到了在单词是否真实时返回 bool 值的方法 (.dictionaryHasDefinitionForTerm
),我还寻找了一种可以返回随机单词的方法。
遗憾的是,这种方法似乎并不存在。我意识到我可以探索 3rd 方 API,但是如果可能的话我更愿意远离它们。
我想也许我可以随机排列所有字母,然后检查它们是否构成一个真实的单词,但这似乎……好吧……愚蠢。
有人知道生成随机词的方法吗?
我也不想手动制作一长串数千个单词,因为我担心内存错误。我还想尝试学习一些语法和新方法,而不是如何导航列表。
最佳答案
我的 /usr/share/dict/words
文件是 /usr/share/dict/words/web2
的符号链接(symbolic link),这是 1934 年的韦氏第二国际词典。该文件只有 2.4mb,因此将整个内容加载到内存中不会对性能造成太大影响。
这是我编写的一个小的 Swift 3.0 代码片段,用于从字典文件中加载一个随机单词。请记住在运行前将文件复制到应用程序的包中。
if let wordsFilePath = Bundle.main.path(forResource: "web2", ofType: nil) {
do {
let wordsString = try String(contentsOfFile: wordsFilePath)
let wordLines = wordsString.components(separatedBy: .newlines)
let randomLine = wordLines[numericCast(arc4random_uniform(numericCast(wordLines.count)))]
print(randomLine)
} catch { // contentsOfFile throws an error
print("Error: \(error)")
}
}
swift 2.2:
if let wordsFilePath = NSBundle.mainBundle().pathForResource("web2", ofType: nil) {
do {
let wordsString = try String(contentsOfFile: wordsFilePath)
let wordLines = wordsString.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let randomLine = wordLines[Int(arc4random_uniform(UInt32(wordLines.count)))]
print(randomLine)
} catch { // contentsOfFile throws an error
print("Error: \(error)")
}
}
Swift 1.2 片段:
if let wordsFilePath = NSBundle.mainBundle().pathForResource("web2", ofType: nil) {
var error: NSError?
if let wordsString = String(contentsOfFile: wordsFilePath, encoding: NSUTF8StringEncoding, error: &error) {
if error != nil {
// String(contentsOfFile: ...) failed
println("Error: \(error)")
} else {
let wordLines = wordsString.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let randomLine = wordLines[Int(arc4random_uniform(UInt32(wordLines.count)))]
print(randomLine)
}
}
}
关于ios - 在 Swift 中生成一个随机词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31212658/