Creating a random number in Swift

I read at https://www.hackingwithswift.com/read/35/2/generating-random-numbers-in-ios-8-and-earlier that the best way to generate a random number is to use

let r = arc4random_uniform(UInt32(_names.count)) let name : String = _names[Int(r)] 

but it seems strange that I have to cast twice to get a random number, what should I do to avoid casting?

+5
source share
5 answers

It depends on how many castings you want to avoid. You can simply wrap it in a function:

 func random(max maxNumber: Int) -> Int { return Int(arc4random_uniform(UInt32(maxNumber))) } 

So, you need to do only ugly casting. Everywhere you want to get a random number with a maximum number:

 let r = random(max: _names.count) let name: String = _names[r] 

As a side note, since it's Swift, your properties don't need _ in front of them.

+6
source

I really like to use this extension

 extension Int { init(random range: Range<Int>) { let offset: Int if range.startIndex < 0 { offset = abs(range.startIndex) } else { offset = 0 } let min = UInt32(range.startIndex + offset) let max = UInt32(range.endIndex + offset) self = Int(min + arc4random_uniform(max - min)) - offset } } 

Now you can create a random Int denoting a range

 let a = Int(random: 1...10) // 3 let b = Int(random: 0..<10) // 6 let c = Int(random: 0...100) // 31 let d = Int(random: -10...3) // -4 
+3
source

you can use gameplaykit

 let random = GKRandomDistribution(lowestValue: 0, highestValue: 100) let r = random.nextInt() 
+1
source

Luca's modified answer written as an extension in Swift 4

 /// Returns random number within given range, upper bound included, eg. -1...0 = [-1, 0, 1] extension CountableClosedRange where Bound == Int { var random: Int { let range = self let offset: Int = range.lowerBound < 0 ? abs(range.lowerBound) : 0 let min = UInt32(range.lowerBound + offset) let max = UInt32(range.upperBound + offset) let randomNumber = Int(min + arc4random_uniform(max - min + 1)) - offset return randomNumber } } /// Returns random number within given range, upper bound not included, eg. -1...0 = [-1, 0] extension CountableRange where Bound == Int { var random: Int { let range = self let offset: Int = range.lowerBound < 0 ? abs(range.lowerBound) : 0 let min = UInt32(range.lowerBound + offset) let max = UInt32(range.upperBound + offset) let randomNumber = Int(min + arc4random_uniform(max - min)) - offset return randomNumber } } 

Examples:

 (0...10).random (0..<10).random 
+1
source

Or you can use

  let name : String = _names[ Int(arc4random()) % _names.count ] 
0
source

Source: https://habr.com/ru/post/1243271/


All Articles