Swift range containment operator

So not everyone knows ~= operator — it’s an pattern matching operator to check whether the range on the left includes the value on right. The definition of this function goes like this.

function ~=

It’s basically the same function as contains just wrapped in operator.

function contains

Usage of the function is the same as the use of the operator.

(1...10).contains(5) // true

which is the same as

1...10 ~= 5 // true

So it makes sense that following like doesn’t work.

(5).contains(1...10) // failure

5 ~= 1...10 // failure

But depending whether the user knows where does ~= come from it may be not obvious why the usage of the operator is one way only. In the written form the word contains implicates the left side is an container for the element on the right side. Like basket contains fruits.

So what’s the point of this post?

While I understand the reasoning why ~= operator is one sided — but for me it’s somehow against the intuition. Normally for if's I write

if someVariable == 3 { doSomething() } ,

so for me it’s more natural to write

if someVariable ~= 1...3 { doSomething() } ,

which is forbidden by default.


So I’ve created simple extension that allows both way usage of this operator to help my against going the logic and reasoning intuition.

Documentation borrowed from original Apple implementation.

Hope that anyone likes going against the grain and finds this useful.