The Conditional Statements in Swift - Swift Academy: The Stress Free Way To Learning Swift Inside & Out (2014)

Swift Academy: The Stress Free Way To Learning Swift Inside & Out (2014)

Chapter 5. The Conditional Statements in Swift

Often, you have to run code snippets based on some criteria. For example, you may need to run additional statements whenever an error occurs, or to show a notification whenever a certain value reaches its maximum or minimum limit. To accomplish this, you have to write “conditional statements.”

The Swift language offers two methods to include conditional statements to your codes. These methods are the “if” and “switch” statements. Usually, you will utilize “if” statements to assess simple conditions that involve few outcomes. The switch statement, on the other hand, is ideal for complicated situations that present many permutations. Programmers use switch statements to run appropriate codes via pattern-matching.

Let’s discuss these conditional statements in detail:

The If Statement

In its most basic form, an “if statement” involves one if condition. “If statements” run a statement (or a group of statements) if the assigned condition is true. Here’s an example:

var temperatureInCelcius = 40

if temperatureInCelcius >= 35 {

println(“It’s so hot. I need some ice cream.”)

In this example, the “if statement” checks if the temperature is greater than or equal to 40 degrees Fahrenheit. If the result is “true”, the system will display the assigned message. If the result is “false”, however, the system won’t show any message – it will simply execute the codes after the current “if statement.”

Swift allows you to add an “else clause” to your “if statements.” An “else clause” is an alternative statement that will be executed if the “if statement’s” condition evaluates to “false.” You have to indicate each else clause using “else” (i.e. a Swift keyword). The code snippet below will illustrate this idea:

temperatureInCelcius = 30

if temperatureInCelcius >= 35 {

println(“It’s so hot. I need some ice cream.”)

} else {

println(“The temperature is still bearable. I’ll just drink some water.”)

}

// prints “The temperature is still bearable. I’ll just drink some water. “

In this example, the system will always print one of the assigned statements. Since the temperature went down to 30 degrees Celcius, the author doesn’t want to eat some ice cream anymore, thus, the system triggered the “else clause” instead.

Swift allows you to add additional clauses by chaining different “if statements.” Here’s an example:

temperatureInCelcius = 5

if temperatureinCelcius >= 35 {

println(“It’s so hot. I need some ice cream.”)

} else if temperatureInCelcius <= 10 {

println(“It’s cold. I need to wear my scarf.”)

} else {

println(“The temperature is still bearable. I’ll just drink some water.”)

// prints “It’s cold. I need to wear my scarf.”

In the example given above, the author added an extra “if statement” to have a response to cold temperatures. This additional statement, although placed in the middle of the code, doesn’t affect the other “if statements.”

The Switch Statement

Switch statements analyze a value and compare it with multiple patterns. They will execute the right code snippet based on the pattern that matches the value. If multiple matches are found, then the system will run the first match that the switch statements have discovered.

Basically, switch statements compare a value with one or more values that belong to the same type. Here’s the syntax that you need to use when using a switch statement:

switch the_value_you_want_to_check {

case first_value:

response_to_the_first_value

case second_value,

third_value:

response_to_the_second_or_third_value

default_response:

Otherwise, run the statements after this switch

}

Each Switch statement contains several cases, each of which starts with “case” (i.e. a Swift keyword). Aside from comparing with particular values, the Swift language allows all cases to specify complicated matching patterns.

Switch cases have a body that is similar to that of “if statements.” Switch statements identify the branch that they need to choose. This approach is called “switching on” the value/s that are being analyzed.

Switch statements need to be comprehensive. That means the system should match each value being considered with one of the switch cases. If you don’t need to write a switch case for all possible values, you may set a default case to take care of the values you don’t like to address separately. You have to write this case at the last part of the switch statement. Additionally, you should use the “default” keyword when declaring default cases.

In the example below, a switch statement considers an animal called “anAnimal”:

let anAnimal: Animal = “goldfish”

switch anAnimal {

case “dog”, “cat”, “mouse”, “cow”, “horse”:

println(“\(anAnimal) is a land animal”)

case “squid”, “shark”, “dolphin”, “goldfish”, “piranha”, “whale”:

println(“\(anAnimal) is a sea creature”)

default:

println(“\(anAnimal) isn’t a land animal or a sea creature”)

}

// prints “goldfish is a sea creature”

The first case of the switch statement contains five of the most common land animals. The second case, on the other hand, contains six of the most common sea creatures.

It is difficult (if not impossible) to include all of the existing animals in this switch statement. We’re talking about hundreds of thousands of species here. To make things simpler, the author simply provided a default case to cover animals that aren’t included in the first two cases. With this default case, the author ensures the comprehensiveness of the switch statement.