W1156 Conditional Syntactic Sugar
From Coder Merlin
Revision as of 00:19, 5 February 2020 by Chukwuemeka-tinashe (talk | contribs) (→Chained If-Else Statements)
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Prerequisites[edit]
Introduction[edit]
While it's possible to perform all necessary comparisons with the conditional that we studied earlier, in some cases doing so can become unwieldy and a bit cumbersome. In this experience we'll explore two alternative options.
Chained If-Else Statements[edit]
If-else statements can be chained. This is appropriate when there are a series of mutually exclusive options. Consider:
var color = "Pink"
if color == "Pink" {
print("Mix red and white")
} else if color == "Orange" {
print("Mix red and yellow")
} else if color == "Green" {
print("Mix yellow and blue")
} else if color == "Purple" {
print("Mix blue and red")
}
A flowchart demonstrating a chained conditional follows:
Caution
It's very important to note that the conditions are evaluated in order. After the first match, the following statement (after the chained conditional) will be executed, even if another match further down the chain would have evaluated to true.