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.
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.
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
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
}