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.
if StatementUse 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.
let temperature = 30if temperature > 25 { print("It is a hot day!") }
else StatementYou can attach an else statement to an if block.
The else block will execute if the if condition evaluates to false.
let isRaining = trueif isRaining { print("Take an umbrella.") } else { print("Enjoy the sunshine.") }
else if StatementUse 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.
let time = 14if time < 12 { print("Good morning!") } else if time < 18 { print("Good afternoon!") } else { print("Good evening!") }
Are parentheses `()` required around the condition in a Swift if statement?