Swift: Else Statement

Else Statement in Swift:

The else statement in Swift is a tool that is frequently used with an if statement.

When the condition of an if statement is false, the else statement is used to run a block of code. Otherwise, consider what else could be used to replace the term. If a condition is met, proceed; otherwise, proceed as follows:

The structure of if-else is as follows:

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

There are two rules to remember:

  • An else statement can only use in conjunction with an if statement and cannot use independently.
  • An else statement is followed by a code block and does not accept a condition.

We created an if statement in the previous exercise that prints a friendly message to Signed in users. To finish this logic and print a message to users who aren’t Signed in, we’ll use an else statement:

var SignIn = false;
 
if SignIn {
  print("Welcome!");
} else {
  print("Access is not permitted."); 
}

Our condition is false because the value of SignIn is false, and the code block after the else will execute.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: