jeudi 29 octobre 2015

How to rewrite code for a (too) big IF statement?

I have a project with some UIbuttons with different UIimages displayed in it. Through user interaction, there could be any of the UIimages in the UIButtons. There are like around 1000 images in the project. I have initialised a variable named 'i'. And a IBAction named buttonTapped on all the buttons. Now I want to update variable 'i' and use the value of 'i' for every different possible `UIImage'. I can do this with an IF statement as shown here:

@IBAction func buttonTapped(sender: UIButton) {

if sender.currentImage == UIImage(named: "image1") {

    i = 1

    print(i)
    // use the value of i

} else if sender.currentImage == UIImage(named: "image2") {

    i = 2

    print(i)
    // use the value of i

} else if sender.currentImage == UIImage(named: "image3") {

    i = 3

    print(i)
    // use the value of i

     } else if // and so on

But I would like a better solution then an IF statement with around 1000 else if(s). I have tried, but I am not able to rewrite the code in a concise matter. What could I use instead of the IF statement? Some kind of loop?

Aucun commentaire:

Enregistrer un commentaire