有没有办法缩短if语句?

时间:2015-03-09 23:41:08

标签: swift if-statement uiimage ibaction arc4random

我想知道是否有一种方法可以缩短以下代码。我过去曾为其他Xcode项目做过同样的事情,而且非常耗时。这是代码:

@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

    }
    }

是否有一种更简单的方法来编写基本相同信息但条件略有不同的if语句?

提前致谢。

1 个答案:

答案 0 :(得分:1)

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