Generate a random number between 0 and 100

This is my current code:

let min = UInt32(0)
let max = UInt32(100)

@IBOutlet weak var percent: UILabel!

@IBAction func finalButton(sender: AnyObject) {
    func randNum (min: Int , max: Int) -> Int {
        return min + Int(arc4random_uniform(UInt32(max - min + 1)))

    }
    percent.text = "\(randNum)+'%'"
}

      

When I run this it works fine until the button is clicked then I get a signal error even though all my code is connected when I look in the connection inspector. Is there a mistake in this code?

+3


source to share


2 answers


I think you are looking for something like this:

let min = 0
let max = 100

@IBOutlet weak var percent: UILabel!

func randNum (min: Int , max: Int) -> Int {
    return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}

@IBAction func finalButton(sender: UIButton) {
    let randomNumber = randNum(min, max: max)
    percent.text = "\(randomNumber)" + "%"
}

      



The function randNum

you are using is looking for the types Int

you need to pass into it. You are not passing any values ​​to the function. Also, you have a function randNum

inside your function UIButton

. Is there a specific reason for this?

+2


source


Try the following:



let randomNumber = randNum(min, max)
percent.text = "\(randomNumber)%"

      

+1


source







All Articles