My /usr/share/dict/wordsfile is a symbolic link to /usr/share/dict/words/web2Webster’s Second International Dictionary since 1934. The file is only 2.4 MB in size, so you should not see too much performance loading all the contents into memory.
Here is a small Swift 3.0 snippet that I wrote to load a random word from a dictionary file. Remember to copy the file to your application package before starting.
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 {
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 {
print("Error: \(error)")
}
}
Swift 1.2 snippet:
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 {
println("Error: \(error)")
} else {
let wordLines = wordsString.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let randomLine = wordLines[Int(arc4random_uniform(UInt32(wordLines.count)))]
print(randomLine)
}
}
}
source
share