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

Chris C

Last Updated on

Feb 16 2023

Written by Iñaki Narciso
Written for Swift 5.7

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!

Table of contents

    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris
    0 Shares
    Share
    Tweet
    Pin
    Share
    Buffer