Create a random word in Swift

I am trying to learn the Swift programming language. I was looking for the Swift API and I found a class UIReferenceLibraryViewController. I found a method that returns bool if the word is real or not ( .dictionaryHasDefinitionForTerm), and I also looked for a method that can return a random word.

Unfortunately, this method does not seem to exist. I understand that I can research third-party APIs, but I prefer to stay away from them if possible.

I thought that maybe I could go through random permutations of all the letters and then check if they form a real word, but it seems ... well ... stupid.

Does anyone know a way to generate a random word?

I also do not want to manually compose a long list of thousands of words, because I am afraid of a memory error. I want to try also to learn some syntax and new methods, and not how to navigate through lists.

+4
source share
2 answers

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 { // 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 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 {
            // String(contentsOfFile: ...) failed
            println("Error: \(error)")
        } else {
            let wordLines = wordsString.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())

            let randomLine = wordLines[Int(arc4random_uniform(UInt32(wordLines.count)))]

            print(randomLine)
        }
    }
}
+6
source

I suggest you check out this project. The guy has already done the following for you!

LoremSwiftum

LoremSwiftum - lorem ipsum iOS, Swift. (, , ), (, URL-, ..) - iOS (UIImage). LoremIpsum, Objective-C.

https://github.com/lukaskubanek/LoremSwiftum

(~ 300 ) , .

https://github.com/lukaskubanek/LoremSwiftum/blob/master/Sources/LoremSwiftum.swift

+2

All Articles