Using Switch/Case in Swift

A switch statement is a form of a conditional statement similar to the if statement. If you’ve seen if statements before, learning how to use the switch statement should be fairly easy.
Written by

Iñaki Narciso

Updated on

Apr 29 2024

Table of contents

    A switch statement is a form of a conditional statement similar to the if statement. If you’ve seen if statements before, learning how to use the switch statement should be fairly easy.

    Put simply, the difference between the two is that the if statement is better suited to check on simple conditions with a few possible outcomes, while the switch statement can do what an if statement does but more. I’ll show you in a bit what a switch statement can do, but first, let’s look at the syntax for a switch condition: switch syntax

    Basically, in a switch statement, you need to provide some value that will then be matched against several possible patterns described by the case values.

    let letter = "a"
    switch letter {
    case "a":
    	print("the first letter of the alphabet")
    case "z":
    	print("the last letter of the alphabet")
    default:
    	print("a letter in between the alphabet")
    }
    

    Each case value will have a code block that will get executed should it matches the value being evaluated by the switch statement. The code block that gets executed will be the first successful case that matches the value.

    In the code snippet above, the switch statement considers a value provided by the letter variable. Since the initial value is "a", it should printout the first letter of the alphabet on the console.

    The switch statement in the snippet above also considers another case for "z". However, since it would be impractical to provide all possible values from the letters of the alphabet, the default case handles this by providing an alternative code block for execution.

    This is similar to writing an if statement as follows:

    let letter = "a"
    if letter == "a" {
    	print("the first letter of the alphabet")
    } else if letter == "z" {
    	print("the last letter of the alphabet")
    } else {
    	print("a letter in between the alphabet")
    }

    This is just the tip of the iceberg for using switch statements. In the next articles, we’ll discuss the use of compound switch cases, and why using the switch statement is better when we need to match for a specific set of values.

    If you want to read more about the basics of the switch syntax or conditional control flow statements in general, please check the Swift official docs.



    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris