W1156 Conditional Syntactic Sugar

From Coder Merlin
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]