Swift If...Else

Swift If...Else Statements

Conditional statements are used to perform different actions based on different conditions.

The if statement is the most common way to make decisions in Swift.

It evaluates a boolean condition (true or false) and executes a block of code only if the condition is true.


The if Statement

Use the if statement to specify a block of Swift code to be executed if a condition is true.

Unlike C or Java, Swift does not require parentheses () around the condition, but curly braces {} are mandatory.

Basic If Statement:

let temperature = 30

if temperature > 25 { print("It is a hot day!") }


The else Statement

You can attach an else statement to an if block.

The else block will execute if the if condition evaluates to false.

If...Else Example:

let isRaining = true

if isRaining { print("Take an umbrella.") } else { print("Enjoy the sunshine.") }


The else if Statement

Use else if to specify a new condition to test, if the first condition is false.

You can chain as many else if statements as you need.

Else If Example:

let time = 14

if time < 12 { print("Good morning!") } else if time < 18 { print("Good afternoon!") } else { print("Good evening!") }


Exercise

Are parentheses `()` required around the condition in a Swift if statement?