Search code examples
swiftrandomarc4random

How to compare random numbers in Swift


I’m a beginner in programming and playing around with the arc4random_uniform() function in Swift. The program I’m making so far generates a random number from 1-10 regenerated by a UIButton. However, I want the variable ’highest' that gets initialised to the random number to update if the next generated number is larger than the one currently held in it. For example the random number is 6 which is stored in highest and if the next number is 8 highest becomes 8. I don't know how to go about this. I have connected the UIButton to an IBAction function and have the following code:

    var randomValue = arc4random_uniform(11) + 1
    highest = Int(randomValue)

    if (Int(randomValue) < highest) {
        // Don’t know what to do
    }

Solution

  • Initialise highest to 0

    Every time you generate a new random number, replace the value of highest with the higher of the two numbers

    highest = max(highest, randomValue)
    

    The max() function is part of the Swift standard library and returns the larger of the two passed in vales.

    edited to add

    Here's a playground showing this with a bit more detail, including casting of types:

    var highest: Int = 0
    
    func random() -> Int {
        let r = arc4random_uniform(10) + 1
        return Int(r)
    }
    
    var randomValue = random()
    highest = max(highest, randomValue)
    

    You can see that multiple calls persist the highest value.

    enter image description here