Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a Random Word in Swift

Tags:

ios

swift

swift2

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

Sadly, this method does not seem to exist. I realize that I can explore 3rd party APIs, however I prefer to stay away from them if possible.

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

Does anybody know of a way to generate a random word?

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

like image 478
Daniel Avatar asked Jul 03 '15 18:07

Daniel


4 Answers

My /usr/share/dict/words file is a symbolic link to /usr/share/dict/words/web2, Webster's Second International Dictionary from 1934. The file is only 2.4mb, so you shouldn't see too much of a performance hit loading the entire contents into memory.

Here's a small Swift 3.0 snippet I wrote to load a random word from the dictionary file. Remember to copy the file to your Application's bundle before running.

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)
        }
    }
}
like image 177
JAL Avatar answered Oct 20 '22 02:10

JAL


I suggest you to check this project. A guy have already done the following for you!

LoremSwiftum

LoremSwiftum is a lightweight lorem ipsum generator for iOS written in Swift. It supports generating texts in different formats (words, sentences, paragraphs), miscellaneous data (names, URLs, dates etc.) and placeholder images for iOS (UIImage). This is a reimplementation of the project LoremIpsum written in Objective-C.

https://github.com/lukaskubanek/LoremSwiftum

This project has only single swift file.( ~300 lines) Therefore, I think reading the file will help you.

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

like image 32
Wonjung Kim Avatar answered Oct 20 '22 04:10

Wonjung Kim


Get random word of length 5.

func randomWord() -> String
    {
        var x = "";
        for _ in 0..<5{
            let string = String(format: "%c", Int.random(in: 97..<123)) as String
            x+=string
        }
        return x
     }
like image 3
Amanpreet Singh Avatar answered Oct 20 '22 03:10

Amanpreet Singh


Try this snippet

struct RandomWordGenerator {
    private let words: [String]
    
    func ranged(_ range: ClosedRange<Int>) -> RandomWordGenerator {
        RandomWordGenerator(words: words.filter { range.contains($0.count) })
    }
}

extension RandomWordGenerator: Sequence, IteratorProtocol {
    public func next() -> String? {
        words.randomElement()
    }
}

extension RandomWordGenerator {
    init() throws {
        let file = try String(contentsOf: URL(fileURLWithPath: "/usr/share/dict/words"))
        self.init(words: file.components(separatedBy: "\n"))
    }
}
like image 3
Alkenso 'Volodymyr Vashurkin' Avatar answered Oct 20 '22 02:10

Alkenso 'Volodymyr Vashurkin'