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!
rand()
in most programming environments gives you a repeatable sequence of pseudo-random numbers, by design. Look for a function calledseed
orsrand
for ways to initialize the random number generator.Using
rand()
is fine, you can seed the pseudo-random number generator with this call at the beginning of your program:You should never use
rand()
, usearc4random
- it's a much better generator. If you check its man-pages, you'll find that it has an integer range generator form calledarc4random_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:The
+ 1
is because the upper end ofarc4random_uniform()
is non-inclusive. If your range is(4,7)
, this should give occurrences of 4, 5, 6, and 7.