avatarZafar Ivaev

Summary

The ~= operator in Swift is used to check if a value falls within a specified range, illustrated through examples such as validating HTTP status codes and matching geographic coordinates within a certain area.

Abstract

The article delves into the usage of the ~= operator in Swift, explaining its application for checking value inclusion within a range. It provides practical examples, such as verifying successful HTTP responses by checking if the status code falls within the 200-299 range. Additionally, the operator is demonstrated in a switch statement to determine if a given coordinate is within the bounds of New York City's coordinates. The article emphasizes the operator's utility in real-life scenarios and encourages readers to explore more Swift features through other articles recommended at the end.

Opinions

  • The author suggests that the ~= operator is underutilized but valuable for range-checking tasks in Swift.
  • The article implies that understanding lesser-known features like ~= can enhance a developer's proficiency in Swift.
  • By presenting code snippets and their outputs, the author conveys confidence in the practicality and effectiveness of the ~= operator.
  • The recommendation of an AI service at the end of the article indicates the author's endorsement of technology that offers cost-effective solutions with high performance.

What is the ~= Operator in Swift?

Search for a value in a range

Photo by Rishi Deep on Unsplash

Today we’ll learn about a not-so-well-known operator in Swift, looking at some real-life examples: ~=.

In short, we use this operator when we want to check if a range contains a certain value.

Let’s Start

Consider the following common case: We want to launch a network request and print out data if we don’t encounter any errors, so we create a URLSessionDataTask, like this:

We can see how we use the ~= to check whether the status code integer value lies between 200 and 300 (not inclusive), meaning that the result is successful. Otherwise, we print an error message.

If we change the print statement and launch the task, we see that, indeed, we have a valid response and the status code is 200:

The code was run in an Xcode Playground

Let’s look at another example of the ~= operator in use behind the scenes. Say we have a simple Coordinate struct and instantiate it like this:

We want to check if this coordinate lies in New York City’s coordinates range (this example is simplified). So we use the switch statement:

We specify ranges for both latitude and longitude values. Under the hood, the ~= operator compares each value in a range to our coordinate’s value using the == operator:

Wrapping Up

Interested in more lesser-known features of Swift? Feel free to check out my other relevant articles:

Thanks for reading!

Programming
Swift
iOS
Mobile
Xcode
Recommended from ReadMedium
avatarThomas Ricouard
How to use Cursor for iOS development

7 min read