Random Alphanumeric String Linux Swift 3

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

    Figured it out.

    So the answer to the repeating random number/string was to just add this line before i called the random() function

    srand(UInt32(time(nil)))
    

    and I'm assuming thats what fixed the illegal instruction also. Because i don't recall changing anything else.

    Needless to say here is my final result

     func generateRandomNumber() -> Int
     {
        var place = 1
    
        var finalNumber = 0;
    
        #if os(Linux)
    
        srand(UInt32(time(nil)))
    
        for _ in 0..<5
        {
            place *= 10
    
            let randomNumber = Int(random() % 10) + 1
    
            finalNumber += randomNumber * place
        }
        #else
        for _ in 0..<5
        {
            place *= 10
    
            let randomNumber = Int(arc4random_uniform(10))
    
            finalNumber += randomNumber * place
        }
        #endif
    
         return finalNumber
     }
    
    
    
     func randomString(_ length: Int) -> String
     {
    
        let letters : String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let len = letters.characters.count
    
        var randomString = ""
    
        #if os(Linux)
    
        srand(UInt32(time(nil)))
    
       for _ in 0..

提交回复
热议问题