Swift rand () is not random

Today is my first day with Swift, and I ran into a problem. I use rand to generate a random number, but it gives 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 writes these numbers:

7
5
5
6
6

I also tried this: Int(arc4random(range.1 - range.0)) + range.0 + 1but he said that he could not find an overload for + that takes the provided arguments

I have no idea why this will happen. I would appreciate help, thanks!

+4
source share
3 answers

rand(), arc4random - . man-, , , arc4random_uniform(), , , 2. , : , :

let damage = arc4random_uniform(UInt32(range.1 - range.0) + 1) + UInt32(range.0)

+ 1 , arc4random_uniform() . (4,7), 4, 5, 6 7.

+11

rand() . seed srand .

+8

Using it rand()in order, you can seed the pseudo random number generator with this call at the beginning of your program:

srand(UInt32(time(nil)))
-2
source

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


All Articles