Lesson 12 Challenge 14 Day beginner Challenge

Hello everyone, I just finished Lesson 12 Challenge on the 14 day Challenge, upon checking the solution I saw this comment using If statement a little bit advance. Now Im wondering on how to apply this kind or way of using If statement.

shouldDecrease ? increase() : decrease()

It essentially replaces the if...else form.

So:

if shouldDecrease == false {
    increase()
} else {
    decrease()
}

becomes:

shouldDecrease ? decrease() : increase()

Where this is particularly useful is if an assignment is made within the if...else branches.

So:

var number: Int = 0
if shouldDecrease == false {
    number = number + 1 //or number += 1
} else {
    number = number - 1 //or number -= 1
}

can be pared down to:

var number: Int = 0
number = number + (shouldDecrease ? -1 : 1)

It’s arguable whether the more compact version is more or less understandable. Some people like the ternary operator (testCondition ? trueValue : falseValue), some people hate it.

1 Like

Thank you very much! Sir well explained and easy to understand I’d try searching ways of using If Statement using swift and got no luck. once again thank you sir @roosterboy.

Was looking at the solution for the Lesson 12 Challenge and saw “Use the flag to determine which method to call.” How do you do this? What is the flag? Thanks

Hi Ryan,

The flag that Chris Ching his referring to is the Boolean named shouldDecrease.

It is initially set to false so that the increase() method is called when that flag value is tested in the if statement:

if shouldDecrease == false {
    increase()
}
else {
    decrease()
}

In the following if statement, the number is tested and if greater than 50 the flag is changed to true. If the number is less than zero then it is set to false.

if number > 50 {
    shouldDecrease = true
}
else if number < 0 {
    shouldDecrease = false
}
1 Like

Got it! Thanks for the explanation