Search code examples
iosarraysswiftxcodedice

simple dice app - going in chronological order instead of random one (Xcode - Swift)


what I need to change in this piece of code in Xcode(Swift) to make the dices go chronologically from 1 to 6 (every time I press the button +1)and over again instead of going randomly as it is now ?

enter image description here


Solution

  • Change what you have to the following:
    ** Keep line with let diceArray as is! **

    class ViewController: UIViewController {
      @IBOutlet weak var diceImageView1: UIImageView!
      
      let diceArray = [1,2,3,4,5,6]; /* <- use what you have already
      
      @IBAction func rollButtonPressed(_ sender: UIButton) {
        if(typeof(diceImageView1.image)=="undefined") diceImageView1.image=null;
        switch(diceImageView1.image) {
          case diceArray[0]: diceImageView1.image = diceArray[1]; break;
          case diceArray[1]: diceImageView1.image = diceArray[2]; break;
          case diceArray[2]: diceImageView1.image = diceArray[3]; break;
          case diceArray[3]: diceImageView1.image = diceArray[4]; break;
          case diceArray[4]: diceImageView1.image = diceArray[5]; break;
          default: diceImageView1.image = diceArray[0];
        }
      }
    }
    

    We are checking if(typeof(diceImageView1.image)=="undefined") because I don't know how the code works, so, just to be sure, we set diceImageView1.image=null;.
    At first run, diceImageView1.image shouldn't be equal to any dice side, so default will set it to [0] which is the dice face with 1 on it.
    Consecutive runs will switch to the next one: [0](1) to [1](2) through [4](5) to [5](6).
    Once it's at [5](6), there is no case for that, so default, as above, will set it to [0](1).