Generate a Random Word in Swift

*爱你&永不变心* 提交于 2020-01-29 09:24:04

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/31212658/generate-a-random-word-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!