Learn Swift Programming Conditional Operator

Introduction to Swift Conditionals

On a daily basis, we’re faced with making decisions based on certain conditions; if the weather is beautiful, we’ll go for a walk, or if it’s rainy, we’ll stay in and code!

In Swift, the ability to determine an outcome based on a given condition also exists. It’s known as a conditional.

Conditionals are powerful programming tools that introduce flexibility and complex behavior to a program by allowing it to react to change. Their power comes from being the root of all decision making within an application.

Your computer, for example, contains authentication processes whose logic is handled by conditionals. If you are logged out, access to certain pages on your device may be restricted, or if your are logged in, access will be granted.

In this lesson, we’ll set up our own rules and conditions for programs to follow using Swift’s conditional statements and operators.

Swift If Statement

The if statement is the most basic and fundamental type of conditional in Swift. It is used to execute some code when a given condition is true.

The structure of an if statement is:

if condition {
this code will run if condition is true
}

 

      • The if keyword is followed by a condition whose value must be true or false.
      • The condition is immediately followed by a code block.
      • code block is a snippet of code enclosed in a pair of curly braces, { }.
      • The code block is executed only when the condition is true.
      • If the condition is false, the code block does not run.

Suppose we’re creating an app that includes an authentication process. We’d declare the variable, isLoggedIn to be true and set up the following if statement that prints a message to users who are logged in:

var isLoggedIn = true if isLoggedIn { print(“Welcome back!”) }

Since the value of the condition is true, the message, Welcome back! will get printed. If isLoggedIn was false, thus our condition false, the code block wouldn’t execute and nothing would get printed.

 

Swift  Else Statement

A tool most commonly used together with an if statement is the else statement.

An else statement is used to execute a block of code when the condition of an if statement is false. Think of the else to be synonymous with the word, otherwise. Do this if a condition is true, otherwise, do something else:

if condition {
   this code will run if condition is true
} else {
   this code will run if condition is false 
}

Two rules to remember:

  • An else statement must be used in conjunction with an if statement and cannot stand on its own.
  • An else statement does not accept a condition and is immediately followed by a code block.

In the previous exercise, we created an if statement that prints a friendly message to logged in users. Let’s use an else statement to complete this logic and print a message to users who are not logged in:

var isLoggedIn = false
if isLoggedIn {
print("Welcome back!") 
} else {
print("Access Denied.") 
}
// Prints: Access Denied.

Since the value of isLoggedIn is false, our condition is therefore, false, and the code block following the else will execute.

Swift  Comparison Operators

So far, our conditions have consisted of a single variable whose value is a Boolean, true or false. With the help of operators, we can expand on this and create conditions that utilize multiple values to achieve a Boolean result.

In this exercise, we’ll learn about one particular group of operators in Swift known as comparison operators. Comparison operators determine the relationship between two operands and return a Boolean value as a result.

Swift supports the following comparison operators:

  • == Equal to
  • != Not Equal to
  • > Greater than
  • < Less than
  • >= Greater than or equal to
  • <= Less than or equal to

Comparison operators are most commonly used to compare numerical values such as Integers and Doubles, though == and != can also be used to compare String values.

4 < 5 // true
0.5 > 0.1 // true
3.5 <= 3.0 // false
12 >= 15 // false
"A" == "A" // true
"B" != "b" // true

Notice how a capital "B" is not equal to a lowercase "b" since Swift is a case sensitive language.

Combining our knowledge of if/else statements and comparison operators, we can construct the following conditional to check for a student’s grade on an exam:

let grade = 95
if grade > 65 {
print("You passed!") 
} else {
print("You failed.")
}

Since the student’s grade is greater than 65, the first code block gets executed and prints, You passed! 🎉.

Swift Else If Statements

Until now, we’ve been working with conditionals that can handle only one condition. If that condition is met, our program follows one course of action, otherwise it follows another.

Swift provides us with a tool called the else if statement which allows us to add additional conditions to a standard if/else statement.

Here’s how it works:

if condition1 {
  this code runs when condition1 is true 
} else if condition2 {
  this code runs when condition2 is true 
} else if condition3 {
  this code runs when condition3 is true 
} else {
  this code runs when all previous conditions are false 
}
  • Similarly to an if statement, an else if statement accepts a condition and a code block to execute for when that condition is true.

  • The else if statement exists only between an if and an else and cannot stand on its own like the if statement can.

  • Any number of else if statements can exist between an if and an else.

Working off the previous example, assume we’d like to update the grading scale in a school to use the academic grading scale used in the U.S..

We can translate numerical grades to letter grades, "A""B""C", etc. with the help of multiple else if statements:

let grade = 85
let letterGrade: String
if grade >= 90 {
letterGrade = "A"
} else if grade >= 80 {
letterGrade = "B"
} else if grade >= 70 {
letterGrade = "C"
} else if grade >= 60 {
letterGrade = "D"
} else if grade < 60 {
letterGrade = "F"
} else {
letterGrade = "N/A"
}
print(letterGrade) 
// Prints: B

Since a student’s numerical grade is 85, the first else if statement executes, and the value of letterGrade becomes "B"

Swift  Ternary Conditional Operator

A standard if/else statement can get pretty lengthy – at least 5 lines of code. Many developers prefer to keep their code as concise as possible and favor a shorter syntax. Swift allows us to minimize our if/else statements with a tool called the Swift ternary conditional operator.

The ternary conditional operator, denoted by a ?, offers a shorter, more concise alternative to a standard if/else statement. It executes one of two expressions depending on the boolean result of the condition.

A ternary conditional consists of three parts in the following format:

A \ ? \ B \ : C
  • A is the condition to check for
  • B is the expression to use if the condition is true
  • C is the expression to use if the condition is false

Suppose we’d like to check if an order was placed successfully by a customer and print them a message. We can set up the following if/else statement:

var orderSuccessfullyPlaced = false

if orderSuccessfullyPlaced {
print("Your order was received.")
} else {
print("Something went wrong.")
}

Since the value of our condition is false, the second code block executes and Something went wrong. will print.

With a sprinkle of ternary magic, we can transform our code into one line, a one liner, and achieve the same result:

orderSuccessfullyPlaced ? 
print("Your order was received.") : 
print("Something went wrong.")

Note that although the ternary conditional operator helps us develop shorter code, overusing this syntax can also result in your code being difficult to read. So, use it sparingly!

>> swift ternary operator

Swift Switch Statement

Another type of conditional statement that exists in Swift is the switch statement. The switch statement is a popular programming tool used to check the value of a given expression against multiple cases. The switch statement is a lot more powerful in Swift than it is in other programming languages, thus we’ll be dedicating the next few exercises to explore its features.

Unlike the if statement, a switch statement does not check for the value of a condition and instead finds and matches a case to a given expression.

Let’s take a look at an example where a switch statement can be used. The code below uses multiple else if statements within an if/else to match a landmark to a given city:

var city = "Rome"

if city == "Rapa Nui" { 
print("Moai 🗿")
} else if city == "New York" {
print("Statue of Liberty 🗽")
} else if city == "Rome" {
print("Colosseum 🏛")
} else {
print("A famous landmark is the Eiffel Tower!")
}

Since this code involves a series of else if comparisons, it’s the perfect candidate for a switch statement rewrite:

switch city {
case "Rapa Nui":
print("Moai 🗿")
case "New York": 
print("Statue of Liberty 🗽")
case "Rome":
print("Colosseum 🏛")
default: 
print("A famous landmark is the Eiffel Tower!")
}

Notice how…

  • Our new conditional begins with the switch keyword and is followed by the variable, city which acts as the expression. The value of the expression, originally "Rome", is checked against each case within the switch block.

  • The corresponding code to execute for a case is followed by a colon, :.

  • Once the value has been matched with a case, the code for that case is executed and the switch completes its checking.

  • Very much similar to an else statement, if a matching value isn’t found, the default statement gets evaluated.

 

Swift  Switch Statement: Interval Matching

One super power that the switch statement possesses, is its ability to match values to an expression that exist within intervals. An interval denotes a range used for checking whether a given value lies within that range.

In Swift, a range is indicated by three consecutive dots, ..., also known as the closed range operator. The closed range operator signifies an inclusive range where the first and last values are included in the sequence.

Let’s see these new concepts in action. In the example below, the switch statement determines the value of year and checks which century it belongs to.

 

var year = 1943
switch year {
case 1701...1800:
print("18th century") 
case 1801...1900:
print("19th century")
case 1901...2000: 
print("20th century")
case 2001...2100: 
print("21st century")
default: 
print("You're a time traveler!")
} 
// Prints: 20th century

 

Since the year, 1943, falls between the interval, 1901...2000, the code for the third case is executed and the message, 20th century gets printed.

Fun fact: The first electronic computer was built in 1943! 💻

Swift Switch Statement: Compound Cases

Another noteworthy ability of the switch statement is its use of multiple values in a single case. These are known as compound cases. The switch statement will match each value within a compound case to the given expression.

The following code checks the value of country and determines the continent on which it is located using a switch statement. Since a continent may consist of multiple countries, compound cases deem useful:

var country = "India"
switch country {
case "USA", "Mexico", "Canada":
print("\(country) is in North America. 🌏")
case "South Africa", "Nigeria", "Kenya":
print("\(country) is in Africa. 🌍")
case "Bangladesh", "China", "India":
print("\(country) is in Asia. 🌏")
default: 
print("This country is somewhere in the world!")
} 
// Prints: India is in Asia. 🌏

Notice how…

  • The multiple values or items in a compound case are separated by a comma.
  • We used string interpolation to output the value of country within the String of the print() statement.

Swift Switch Statement: where Clause

Another neat feature available for the cases of a switch statement is the where clause.

The where clause allows for additional pattern matching for a given expression. It can also be used with loops and other conditionals such as if statements.

Assume we’re creating a program that determines if a random integer between 0 and 10 is even or odd. We can write the following program:

let randomNumber = Int.random(in: 0...10)

switch randomNumber {
case let x where x % 2 == 0:
print("\(randomNumber) is even")
case let x where x % 2 == 1:
print("\(randomNumber) is odd")
default:
print("Invalid")
}

Let’s dive into what’s happening on the first line:

let randomNumber = Int.random(in: 0...10)
  • We’re generating a random integer, Int, using the built in Swift method, .random() which returns an arbitrary value from a range of numbers. Notice how we’re using the closed range operator, ..., to denote a numerical range.

  • We then assign the randomly generated value to randomNumber. We’ll be working more with .random() in the following lessons.

Following the variable declaration is a standard switch statement that checks the value of randomNumber:

switch randomNumber {
case let x where x % 2 == 0:
print("\(randomNumber) is even")
case let x where x % 2 == 1:
print("\(randomNumber) is odd")
default:
print("Invalid")
}

// Prints: 7 is odd
  • Each case contains a variable declaration followed by a where clause and a condition. When a condition is true, the code for that case will execute.

  • The let keyword followed by the x creates a temporary binding to the randomNumber value. This means that the value of x temporarily becomes the value of randomNumber. If randomNumber is 5, then x is 5!

  • The let keyword is specifically used here instead of var since the value of x will not be reassigned at any point throughout the switch statement, thus it’s value always constant. If var is used, Swift will display a compiler warning recommending us to use let instead:

Numbers.swift:6:12: warning: variable 'x' was never mutated; consider changing to 'let' constant

Note: a compiler warning is not an error. Your program should still run even with a warning.

  • Lastly, the where condition checks if x is divisible by 2 with or without a remainder and determines if the randomNumber is even or odd.

If you run this code, chances are your output will be different from ours since the number generated each time is random!

>>  Best Django Hosting 2020

Swift conditional Review

Excellent work! In this lesson, we’ve learned the following concepts:

  • An if statement consists of a condition and code block that executes when the condition is true.
  • An else statement is immediately followed by a code block that executes when all previous conditions were false.
  • code block is denoted by a set of curly braces {}.
  • Multiple else if statements can be chained within an if/else to provide additional conditions.
  • Comparison operators include <><=>===, and != and are used to compare the values of two operands.
  • switch statement looks for the value of a case that matches the value of an expression.
  • switch statement can have cases that contain multiple items known as compound cases.
  • switch statement’s case can include a range of values using the closed range operator (...).

You’ve covered a major fundamental programming concept used in every program to control the logical flow. Feel free to utilize the empty Review.swift file and output terminal on the right to hone your understanding of conditionals and practice writing Swift code.

More Articles:

>> 5 Best Blockchain Books 2020