I'm trying to get this part of the app to work were the user clicks a button and a label prints a randomly generated number between 1-12. I've been able to successfully do that, but I also want it to not repeat any random numbers that have already been printed.
What I've tried doing is putting any printed number into an array, and then checking the array each time it generates a new number.
I've gotten it to work in the Playground, but cannot get it working with a real project.
Here is the code for my project.
var usedNumbers = [Int]()
var randomConv = 0
func randomize() {
lblRandom.text = "\(arc4random_uniform(12) + 1)"
randomConv = Int(lblRandom.text!)!
}
@IBAction func btnRandomPressed(sender: AnyObject) {
randomize()
if usedNumbers.contains(randomConv) {
randomize()
} else {
usedNumbers.append(randomConv)
}
if usedNumbers.count == 12 {
btnRandom.hidden = true
}
}
And here is the code from my playground.
var lblRandom = "\(arc4random_uniform(12) + 1)"
var randomConv = 0
var usedNumbers = [Int]()
func randomize() {
lblRandom = "\(arc4random_uniform(12) + 1)"
randomConv = Int(lblRandom)!
}
repeat {
randomize()
if usedNumbers.contains(randomConv) {
randomize()
} else {
usedNumbers.append(randomConv)
print(lblRandom)
}
} while usedNumbers.count < 12
Aucun commentaire:
Enregistrer un commentaire