swift Swift随机字生成器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift随机字生成器相关的知识,希望对你有一定的参考价值。

//Inspired by: http://planetozh.com/blog/2012/10/generate-random-pronouceable-words/
func randomWord(wordLength: Int = 6) -> String {
    
    let kCons = 1
    let kVows = 2
    
    var cons: [String] = [
        // single consonants. Beware of Q, it"s often awkward in words
        "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
        "n", "p", "r", "s", "t", "v", "w", "x", "z",
        // possible combinations excluding those which cannot start a word
        "pt", "gl", "gr", "ch", "ph", "ps", "sh", "st", "th", "wh"
    ]
    
    // consonant combinations that cannot start a word
    var cons_cant_start: [String] = [
        "ck", "cm",
        "dr", "ds",
        "ft",
        "gh", "gn",
        "kr", "ks",
        "ls", "lt", "lr",
        "mp", "mt", "ms",
        "ng", "ns",
        "rd", "rg", "rs", "rt",
        "ss",
        "ts", "tch"
    ]
    
    var vows : [String] = [
        // single vowels
        "a", "e", "i", "o", "u", "y",
        // vowel combinations your language allows
        "ee", "oa", "oo",
    ]
    
    // start by vowel or consonant ?
    var current = (Int(arc4random_uniform(2)) == 1 ? kCons : kVows );
    
    var word : String = ""
    while ( count(word) < wordLength ){
        // After first letter, use all consonant combos
        if count(word) == 2 {
            cons = cons + cons_cant_start
        }
        
        // random sign from either $cons or $vows
        var rnd: String = "";
        var index: Int;
        if current == kCons {
            index = Int(arc4random_uniform(UInt32(cons.count)))
            rnd = cons[index]
        }else if current == kVows {
            index = Int(arc4random_uniform(UInt32(vows.count)))
            rnd = vows[index]
        }
        
        
        // check if random sign fits in word length
        var tempWord = "\(word)\(rnd)"
        if( count(tempWord) <= wordLength ) {
            word = "\(word)\(rnd)"
            // alternate sounds
            current = ( current == kCons ) ? kVows : kCons;
        }

        
        
        
    }
    
    return word
}

以上是关于swift Swift随机字生成器的主要内容,如果未能解决你的问题,请参考以下文章

随机密码生成器 Swift 3?

swift C导入随机数生成器

如何在 Swift 中生成随机数?

为什么在Swift中默认随机生成数字UInt-32?

在 Swift 中随机生成战利品 [关闭]

Swift - Cloud Firestore 中的唯一 ID