Home > Enterprise >  New to Swift (and programming in general). Why is my code calling the wrong action?
New to Swift (and programming in general). Why is my code calling the wrong action?

Time:08-24

I'm a total newbie, so pardon me if this is an annoying question. I am just practicing and am wondering why this code is printing "Almost perfect. Give it another try!" when it should be printing "Well, you got one correct". Any help would be much appreciated

var subjectOne = true
var subjectTwo = false
var subjectThree: Int = 5
func shout(subjectOne: Bool, subjectTwo: Bool, subjectThree: Int){
    if subjectOne && subjectTwo && subjectThree >= 25{
        print("HIGH SCORE!")
    }
    else if subjectOne || subjectTwo && subjectThree >= 10{
        print("Almost perfect. Give it another try!")
    }
    else if subjectOne && subjectTwo && subjectThree >= 10{
        print("There ya' go!")
    }else if !subjectOne && !subjectTwo && subjectThree >= 10{
        print("Well, you got a high enough number at least!")
    }else if subjectOne || subjectTwo && subjectThree < 10{
        print("Well, you got one correct")
    }else if !subjectOne && !subjectTwo && subjectThree < 10{
        print("You fail at life!")
    }else if subjectOne || subjectTwo && subjectThree >= 25{
        print("Almost a high score. Keep going, you got this!")
    }
}
shout(subjectOne: subjectOne, subjectTwo: subjectTwo, subjectThree: subjectThree)

CodePudding user response:

This is happening because your first else if clause is evaluating to true due to order of operations:

else if subjectOne || subjectTwo && subjectThree >= 10

evaluates from left to right, so your code first checks if subjectOne is true. Because it is indeed true, and an || (or) comes next, your code no longer needs to evaluate the rest of the expression because it already evaluates as true.

You might have meant to write that clause this way instead:

else if (subjectOne || subjectTwo) && subjectThree >= 10

This would evaluate to false because thanks to the parenthesis, your code knows that it must evaluate both sides of the expression (subjectOne or subjectTwo) AND subjectThree must be greater than or equal to ten.

  • Related