Daniel
Daniel

Reputation: 3597

Generate a Random Word in Swift

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.

Upvotes: 6

Views: 9795

Answers (5)

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"))
    }
}

// usage example:
let random = try! RandomWordGenerator()
print(random.next()!)
print("3 randoms: \(random.prefix(3).joined(separator: ", "))")
print("Another 3 randoms: \(random.prefix(3).joined(separator: ", "))")

Upvotes: 3

Vijayvir Sing Pantlia
Vijayvir Sing Pantlia

Reputation: 689

Above code will create the paragraph text which can be used to set in label , textview ..

func randomPargraph(pargraph : Int = 40 ) -> String{
        var global = ""
        
        for _ in 0..<(Int.random(in: 2..<pargraph)) {
            
            var x = "";
            for _ in 0..<Int.random(in: 2..<15){
                let string = String(format: "%c", Int.random(in: 97..<123)) as String
                x+=string
            }
            global = global +  " " + x
        }
        
     
        
        return global
     }

Upvotes: 0

Clean Coder
Clean Coder

Reputation: 562

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
     }

Upvotes: 4

JAL
JAL

Reputation: 42489

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)
        }
    }
}

Upvotes: 7

Wonjung Kim
Wonjung Kim

Reputation: 1933

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

Upvotes: 3

Related Questions