Random Alphanumeric String Linux Swift 3

前端 未结 4 891
名媛妹妹
名媛妹妹 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:24

    I copied and pasted your code exactly, and it doesn't compile.

    fatal error: Can't form a Character from an empty String

    Here's an alternative method:

    // Keep at top of your code (outside of functions)
    #if os(Linux)
        srandom(UInt32(time(nil)))
    #endif
    
    
    func getRandomNumber(_ min: Int, _ max: Int) -> Int {
        #if os(Linux)
            return Int(random() % max) + min
        #else
            return Int(arc4random_uniform(UInt32(max)) + UInt32(min))
        #endif
    }
    
    
    func getRandomString(_ chars: String, _ length: Int) -> String {
        var str = ""
    
        for _ in 1...length {
            str.append(chars.itemOnStartIndex(advancedBy: getRandomNumber(0, chars.count - 1)))
        }
    
        return str
    }
    
    
    // Best practice to define this outside of the function itself
    let chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    print(getRandomString(chars, 10))
    

    This works for me on Ubuntu.

提交回复
热议问题