get random text from english dictionary in swift in swift

Here's a code snippet that generates a random word from the English dictionary in Swift:

main.swift
func getRandomWord() -> String? {
    if let path = Bundle.main.path(forResource: "english", ofType: "txt") {
        do {
            let data = try String(contentsOfFile: path, encoding: .utf8)
            let words = data.components(separatedBy: .newlines)
            let randomIndex = Int.random(in: 0..<words.count)
            return words[randomIndex]
        } catch {
            print(error)
        }
    }
    return nil
}
436 chars
14 lines

This function reads the contents of a text file called english.txt that contains a list of English words separated by newlines. It then selects a random word from the list and returns it.

You can call the function like this:

main.swift
if let randomWord = getRandomWord() {
    print(randomWord)
}
62 chars
4 lines

gistlibby LogSnag