Difference between revisions of "W1156 Conditional Syntactic Sugar"

From Coder Merlin
(Created page with "thumb|link=|White Rock Sugar == Prerequisites == * W1151 Conditional and Flow Chart == Introduction == While it's possible to per...")
 
Line 19: Line 19:
}
}
</syntaxhighlight>
</syntaxhighlight>
A flowchart demonstrating a chained conditional follows:
{{ResponsiveImage|[[File:Chained Conditional Flowchart.png]]}}
{{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.
}}
== Key Concepts ==
== Key Concepts ==
== Exercises ==
== Exercises ==
== References ==
== References ==

Revision as of 00:19, 5 February 2020

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
White Rock Sugar

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:

   Chained Conditional Flowchart.png
CautionWarnIcon.png

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.

Key Concepts[edit]

Exercises[edit]

References[edit]