Interval Matching Using Switch in Swift

In this article, we show you how to implement interval matching using switch in Swift and Xcode. Click here to learn more!
Written by

Iñaki Narciso

Updated on

Apr 29 2024

Table of contents

    You may have learned how enums are best used with switch from the previous articles, but wondered how the switch statement handles matching cases with a specific range or interval.

    In Swift, you can create a range of values as a switch case using the built-in range operators.

    A great example of it would be handling the response code from a network call. The response code is a number for a standard HTTP code.

    switch response.code {
    case 200...299:
    	print("Success")
    
    case 400...599:
    	print("Failed")
    
    default:
    	print("Unsupported")
    }

    If the response.code falls to a value within the range of 200 to 299, then the switch statement will print "Success".

    If the code falls to a value within the range of 400 to 599, then the switch statement will print "Failed", since that code pertains to either a client-side or a server-side error.

    Otherwise, it will print "Unsupported".

    That’s all for this post. See you at the next one!



    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris