Kristof.V Kristof.V -4 years ago 123
Swift Question

Random Number (X amount till X amount) swift

here i'm with another question.

I'm now able to pick a random number for my items but..
is it possible to pick a random number between 2 numbers.?

so instead of

let number = (arc4random_uniform(100))


i would like something like this

let number = (arc4random_uniform(10...20))


or something like that..?
now if i get a weapon drop it can be everything in my list.
this way i could make it so that only the first few would have a drop for a specific monster or at higher level they would drop better weapons and not the low levels anymore..

Answer Source

Xcode 8.2 • Swift 3.0.2

extension CountableClosedRange where Bound: Integer {
    var random: Int {
        return Int(lowerBound.toIntMax()) + Int(arc4random_uniform(UInt32((upperBound - lowerBound + 1).toIntMax())))
    }
    func random(_ n: Int) -> [Int] {
        var result: [Int] = []
        result.reserveCapacity(n)
        (0..<n).forEach({ _ in result.append(random) })
        return result
    }

}
extension CountableRange where Bound: Integer {
    var random: Int {
        return Int(lowerBound.toIntMax()) + Int(arc4random_uniform(UInt32((upperBound - lowerBound).toIntMax())))
    }
    func random(_ n: Int) -> [Int] {
        var result: [Int] = []
        result.reserveCapacity(n)
        (0..<n).forEach({ _ in result.append(random) })
        return result
    }
}

Usage:

(10...20).random    // 16
(0...1).random(10)  // [0, 1, 0, 0, 1, 1, 1, 1, 1, 0]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download