How to create a custom operator (like ~= operator) in swift ??

I have seen developers using custom operators which adds meaning to the code and reduce the amount of code required to perform an operation. Creating custom operators are not encouraged. But you still can, if you wish to!!.

Abhimuralidharan
5 min readMay 11, 2018

I was learning about pattern matching in swift and my eyes got stuck on a special operator ~= . I have used this before for pattern matching, But I didn’t knew how it works. I have used ~= operator for checking if the http error fall into any of the given range (wanted to check if error is 4xx excluding 401) like this:

I didn’t had any idea what it does internally. I also didn’t knew that we can also create custom operators like this. So, I asked google about this and he showed me all what I wanted.

Have a look at some of such operators in swift: Defines Swift

Types of Operators

Operators in swift fall into the following types:

  • Infix — Used between two values (ex: <value>+<value>)
  • Prefix — Used before a value (ex: !<value>)
  • Postfix — Used after a value (ex: <value>!)

--

--