Swift: Switch Statement

Switch Statement in Swift:

The switch statement in Swift is another type of conditional statement available in Swift. The switch statement is a common programming tool for comparing the value of a given expression to multiple scenarios. Because the switch statement in Swift is far more powerful than in other programming languages, we’ll spend the next few exercises delving into its capabilities.

A switch statement, unlike an if statement, does not check the value of a condition; instead, it finds and matches a case to a given expression.

Now let us look at an example about how to use the switch statement. To match a landmark to a Country, the code below uses multiple else if statements within an if/else :

var Country = "France";
if Country == "China" { 
  print("The Great Wall of China!");
} else if Country == "United States" {
  print("Central Park!");
} else if Country == "Egypt" {
  print("The Great Pyramid of Giza!");
} else {
  print("I Love Disneyland!");

This code is ideal for a switch statement rewrite because it contains a series of else if comparisons:

switch Country {
  case "China":
    print("The Great Wall of China!");
  case "United States":  
    print("Central Park!");
  case "Egypt":
    print("The Great Pyramid of Giza!");
    print("I Love Disneyland!");

Keep in mind:

  • The switch keyword is follow by the variable, Country, which acts as the expression in our new conditional. The value of the expression, which was originally "France", is compared to each case in the switch block.
  • A colon :, follows the corresponding code to run for a case.
  • The code for that case is executed once the value has been matched with a case, and the switch completes its checking.
  • If no matching value is found, the default statement is evaluated, much like an else statement.

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: