Search code examples
swiftif-statementuiimageibactionarc4random

Is there a way to shorten if-statements?


I am wondering if there is a way to the following code shorter. I have done this same type of thing for other Xcode projects in the past and it has been very time consuming. Here is the code:

@IBAction func flashButton(sender: UIButton) {

    flashButton.hidden = !flashButton.hidden
    flashingImageView.hidden = !flashingImageView.hidden
    flashingImageView.image = UIImage(named: "Image\(arc4random_uniform(6) + 1).png")

    if (flashingImageView.image == UIImage(named: "Image1")){

        randomImageGeneratorNumber == 1

    }

    if (flashingImageView.image == UIImage(named: "Image2")){

        randomImageGeneratorNumber == 2

    }

    if (flashingImageView.image == UIImage(named: "Image3")){

        randomImageGeneratorNumber == 3

    }

    if (flashingImageView.image == UIImage(named: "Image4")){

        randomImageGeneratorNumber == 4

    }

    if (flashingImageView.image == UIImage(named: "Image5")){

        randomImageGeneratorNumber == 5

    }

    if (flashingImageView.image == UIImage(named: "Image6")){

        randomImageGeneratorNumber == 6

    }
    }

Is there is a simpler way to write if-statements that go off basically the same information but have slightly different conditions?

Thanks in advance.


Solution

  • flashButton.hidden = !flashButton.hidden
    flashingImageView.hidden = !flashingImageView.hidden
    randomImageGeneratorNumber = arc4random_uniform(6) + 1 
    flashingImageView.image = UIImage(named: "Image\(randomImageGeneratorNumber).png")