Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use if-else Statements in Swift
Written by Team Kodeco

An if-else statement allows you to make decisions in your code by evaluating a boolean condition. If the condition is true, the code inside the if block will be executed. If the condition is false, the code inside the else block will be executed.

Here is an example of an if-else statement in Swift:

let age = 18

if age >= 21 {
  print("You can drink alcohol")
} else {
  print("You can't drink alcohol")
}
// Output: You can not drink alcohol

In the above example, you define a variable age and assign it a value of 18. Then you use an if-else statement to check if the value of age is greater than or equal to 21.

If it is, the code inside the if block is executed and the message “You can drink alcohol” is printed. If the value of age isn’t greater than or equal to 21, the code inside the else block is executed and the message “You can’t drink alcohol” is printed.

If, Else If and Else

You can also chain multiple if-else statements together using the else if statement. The following example checks for different ranges of ages and prints an appropriate message.

if age < 18 {
  print("You are a minor.")
} else if age >= 18 && age < 21 {
  print("You can vote but can't drink alcohol.")
} else {
  print("You can vote and drink alcohol.")
}
// Output: You can vote but can't drink alcohol.
© 2024 Kodeco Inc.