Learn Courses My Dashboard

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.