I am trying to make a demonstration of superposition in quantum physics using dice. The app is supposed to output a random amount of dice with a random value on each. This is the code intended to get the number of dice and the number for each:

func newDice() {
    var amountOfNumbers = Int(arc4random_uniform(6))+1
    var diceDisplayed: Array<Int> = []
    for var i=1; 1<=amountOfNumbers; ++i {
        var diceNum: Int = Int(arc4random_uniform(6)) + 1
        diceDisplayed.append(diceNum)
    }
}

I plan to add more to this to actually set the dice, but if this didn't work then how would setting the dice work.

This is intended to happen when the device is shaken and I use this function for that:

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
    if motion == .MotionShake {
        newDice()
        resetDice()
    }
}

resetDice() sets all of the UIImageViews for the dice to nil so that no dice are left when the device is shaken again.

func resetDice() {
    for var i=0; i<=5; ++i {
        dice[i].image = nil
    }
}

By default I have the first dice slot set to one in order to test if resetDice() is working. I am using iOS simulator to run the app, and when it is given the shake gesture the CPU usage as recorded in Xcode shoots up to 100% and the RAM usage (also recorded in Xcode) rises slowly until after a long period of time the app crashes, presumably because it runs out of memory. I have tried running the program with newDice() commented out and it runs perfectly.

1

There are 1 answers

2
Nate Cook On BEST ANSWER

In your for loop conditional you have a 1 (the number one) instead of i:

for var i=1; 1<=amountOfNumbers; ++i {
    var diceNum: Int = Int(arc4random_uniform(6)) + 1
    diceDisplayed.append(diceNum)
}

Change it to:

for var i=1; i<=amountOfNumbers; ++i {
    var diceNum: Int = Int(arc4random_uniform(6)) + 1
    diceDisplayed.append(diceNum)
}

And actually, a nicer syntax for that loop in Swift is:

for i in 1...amountOfNumbers {
    var diceNum: Int = Int(arc4random_uniform(6)) + 1
    diceDisplayed.append(diceNum)
}