W1156 Conditional Syntactic Sugar

From Coder Merlin
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
WarnIcon.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.

Switch Statements[edit]

Even more syntactic sugar is provided with the switch statement. The switch statement is suitable for many cases, most often where a single variable is evaluated in each condition. The statement follows the same flowchart as a chained if-else statement.

Review the above example using the chained if-else statement. The identical logic implemented as a switch statement is:

switch color {
case "Pink":
    print("Mix red and white")
case "Orange":
    print("Mix red and yellow")
case "Green":
    print("Mix yellow and blue")
case "Purple":
    print("Mix blue and red")
default:
    print("An unknown color combination is required.")
}

Key Concepts[edit]

Exercises[edit]

References[edit]


Designed with pride in Silicon Valley, CA, USA