Today is my first day with Swift, and I have run into a problem. I am using rand to generate a random number, but it is giving me the same results every time I run the code.
main.swift:
import Foundation
var player = Player()
for _ in 1..6 {
println(player.kick())
}
player.swift:
import Foundation
class Player {
var health = 25
var xp = 15
var upgrades = ["kick": 0, "punch": 0]
func kick() -> Int {
let range = (3, 7)
let damage = Int(rand()) % (range.1 - range.0) + range.0 + 1
return damage
}
func punch() -> Int {
let range = (4, 6)
let damage = Int(rand()) % (range.1 - range.0) + range.0 + 1
return damage
}
}
Every time I run the code, it logs these numbers:
7
5
5
6
6
I also tried this: Int(arc4random(range.1 - range.0)) + range.0 + 1
but it said it couldn't find an overload for + that accepts the supplied arguments
I have no idea why this would be happening. I'd appreciate some help, thanks!
You should never use rand()
, use arc4random
- it's a much better generator. If you check its man-pages, you'll find that it has an integer range generator form called arc4random_uniform()
, which you should use to avoid modulo bias when the modulus is not a power of 2. I believe the following is what you want, it worked for me in playground:
let damage = arc4random_uniform(UInt32(range.1 - range.0) + 1) + UInt32(range.0)
The + 1
is because the upper end of arc4random_uniform()
is non-inclusive. If your range is (4,7)
, this should give occurrences of 4, 5, 6, and 7.
rand()
in most programming environments gives you a repeatable sequence of pseudo-random numbers, by design. Look for a function called seed
or srand
for ways to initialize the random number generator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With