Random Alphanumeric String Linux Swift 3

前端 未结 4 889
名媛妹妹
名媛妹妹 2021-01-20 16:45

Im having 2 problems when trying to generate a random string in Linux with Swift 3.

  1. arc4random_uniform is not available in Linux only on BSD. SO i was able

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-20 17:31

    1) Always the same number

    You have to set a seed once to get "random" numbers from random():

    randomSeed(Int(Date().timeIntervalSince1970)
    

    Man page:

    If no seed value is provided, the random() function is automatically seeded with a value of 1.

    As the seed is always the same (1), you always get the same sequence of "random" numbers.

    2) Alphanumeric string

    To create your string without using NSString:

    func randomString(length: Int) -> String {
    
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let len = UInt32(letters.characters.count)
    
        var randomString = ""
    
        for _ in 0 ..< length {
            let rand = myCustomRandom(len)
            let randIndex = letters.index(letters.startIndex, offsetBy: Int(rand))
            let nextChar = letters[randIndex]
            randomString += String(nextChar)
        }
    
        return randomString
    }
    

提交回复
热议问题