Generate random number of certain amount of digits

后端 未结 7 1926
不知归路
不知归路 2021-01-18 10:51

Hy,

I have a very Basic Question which is :

How can i create a random number with 20 digits no floats no negatives (basically an Int) in Swift ?

Than

7条回答
  •  萌比男神i
    2021-01-18 11:29

    Swift 5: Simple Solution

    func random(digits:Int) -> String {
        var number = String()
        for _ in 1...digits {
           number += "\(Int.random(in: 1...9))"
        }
        return number
    }
    
    print(random(digits: 1)) //3
    print(random(digits: 2)) //59
    print(random(digits: 3)) //926
    

    Note It will return value in String, if you need Int value then you can do like this

    let number = Int(random(digits: 1)) ?? 0
    

提交回复
热议问题