Compound Cases for Switch Statements Using Enums in Swift

In this article, you’ll learn how to use compound cases for switch statements using Swift in Xcode. Click here to know more!
Written by

Iñaki Narciso

Updated on

Apr 29 2024

Table of contents

    Using enums is where the switch statement truly shines as you get the benefits of compiler-safety by forcing you to implement an exhaustive list of cases.

    However, there might be instances where you need to implement the same code block for multiple matching cases.

    For example, we wanted to determine which planets in the Solar system are located before the Asteroid belt, and which ones are located beyond it.

    We can write it out as a switch statement as follows:

    enum Planet {
    	case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
    }
    ...
    switch planet {
    case .mercury: fallthrough
    case .venus: fallthrough
    case .earth: fallthrough
    case .mars:
    	print("This planet is located before the asteroid belt of the Solar system")
    	
    case .jupiter:
    	print("This planet is located within the outer bounds of the asteroid belt, together with the Jupiter trojan group")
    	
    case .saturn: fallthrough
    case .uranus: fallthrough
    case .neptune:
    	print("This planet is located beyond the asteroid belt")
    }

    The fallthrough statement tells the switch that when a match falls to a fallthrough case, it should find the first match that has an executable code block.

    For example, you assign planet = .earth. When it enters the switch statement, it matches with case .earth, but sees it with the fallthrough statement, so it falls through the immediate next case which is .mars. The switch will then execute the code block from the .mars case, and exits the switch statement.

    This is great since we can group multiple cases into executing a single code block, but it is tedious to write.

    To make this easier to write, we can make use of compound cases wherein we key in the different possible values as a group to match a case. This will make the code shorter, and easier to read.

    switch planet {
    case .mercury, .venus, .earth, .mars:
    	print("This planet is located before the asteroid belt of the Solar system")
    	
    case .jupiter:
    	print("This planet is located within the outer bounds of the asteroid belt, together with the Jupiter trojan group")
    	
    case .saturn, .uranus, .neptune:
    	print("This planet is located beyond the asteroid belt")
    }

    That’s all for now! Hope you learned more about the use of switch in Swift.



    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris