-1

im Sorry I´m a litte rusty in coding and i couldn't figure this out. He goes through all the colors till he es back again on blue. After a If statement is true he shouldn't look for the next one. Thanks for your understanding...

@IBAction func didTapLike(){
    
    
    if profilImage.image == UIImage(named: "blue"){
        profilImage.image = UIImage(named: "yellow")
    }
   
    if profilImage.image == UIImage(named: "yellow"){
        profilImage.image = UIImage(named: "green")
    }
    
    if profilImage.image == UIImage(named: "green"){
        profilImage.image = UIImage(named: "purple")
    }
   
    if profilImage.image == UIImage(named: "purple"){
        profilImage.image = UIImage(named: "red")
    }
    
    if profilImage.image == UIImage(named: "red"){
        profilImage.image = UIImage(named: "blue")
    }
    
    else {
        
    }
    
    
    
}
  • Add `return` after each `profileImage.image = newImage`, or use `else if` instead of consecutive `if` (which can also be written with a `switch`)... – Larme Jul 15 '21 at 16:59
  • 1
    You are probably going to get caught by this issue: https://stackoverflow.com/questions/11342897/how-to-compare-two-uiimage-objects Comparing the `UIImage` is probably not the route you want to take. – jnpdx Jul 15 '21 at 17:05
  • Comparing did work but the whole loop doesent. – user14030013 Jul 15 '21 at 17:12
  • Bad idea to compare image references. Even if compare works for you at this moment, one day you will shoot in your leg. Use suggested solution instead - https://stackoverflow.com/a/68399150/1135154 – Kirow Jul 15 '21 at 18:57

2 Answers2

4

A more efficient solution is array based.

In the function the index is incremented.
If the number of items in the array is exceeded the index is reset to 0 by the modulo (%) operator

var colorIndex = 0

@IBAction func didTapLike() {
   let colorArray = ["blue", "yellow", "green", "purple", "red"]
   colorIndex = (colorIndex + 1) % colorArray.count
   profilImage.image = UIImage(named: colorArray[colorIndex])
}

On setup you have to set the image to blue or the index to the corresponding value of the default color.

vadian
  • 274,689
  • 30
  • 353
  • 361
1

Hy use else if, it will be better

    @IBAction func didTapLike(){
    
        if profilImage.image == UIImage(named: "blue") {
            profilImage.image = UIImage(named: "yellow")
        } else if profilImage.image == UIImage(named: "yellow") {
            profilImage.image = UIImage(named: "green")
        } else if profilImage.image == UIImage(named: "green") {
            profilImage.image = UIImage(named: "purple")
        } else if profilImage.image == UIImage(named: "purple") {
            profilImage.image = UIImage(named: "red")
        } else if profilImage.image == UIImage(named: "red") {
            profilImage.image = UIImage(named: "blue")
        } else {  
        }   
    }