我/usr/share/dict/words
文件是一個符號鏈接/usr/share/dict/words/web2
,韋伯斯特的第二屆國際字典從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)")
}
}
雨燕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)")
}
}
雨燕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)
}
}
}
來源
2015-07-16 19:29:15
JAL
「我也不想使數千字的長名單」 那麼,你不知道如何做到這一點,但你會排除做到這一點?你如何想象如果你不是從一組東西開始的話,你可以隨便選一個_anything_?涉及甲板上隨機牌的卡牌技巧需要甲板!如果我伸出空着的手說「拿一張卡片,任何卡片」,你會怎麼做? – matt
好吧,你會開始在房間裏隨意抓東西,檢查它們是否是卡,如果他們不繼續......但我們也已經消除了這個選項。 –
從您的Mac中複製'/ usr/share/dict/words'到您的應用程序包並使用它。 – JAL