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!!.

Image for post
Image for post
Image for post
Image for post

Types of Operators

How to create Custom Operators??

let someVal = 25let squareRoot = someVal // result is 5

Let’s discuss the steps to create one.

prefix operator √
prefix func √(lhs: Double) -> Double {return sqrt(lhs)}
Image for post
Image for post
Custom square root operator in swift

Let us create a custom infix operator using ◉ symbol.

infix operator ◉
infix func ◉(lhs: Double, rhs: Double) -> Double {return lhs * lhs + rhs * rhs}
 func ◉(lhs: Double, rhs: Double) -> Double {return lhs * lhs + rhs * rhs}
Image for post
Image for post

Question: Is that it? Do we have to consider anything else while creating a custom operator??🤔🤔🤔🤔

Precedence and Associativity

If you declare a new operator without specifying a precedence group, it is a member of the DefaultPrecedence precedence group. DefaultPrecedence has no associativity and a precedence immediately higher than TernaryPrecedence.

Image for post
Image for post
Source: raywenderlich
precedencegroup SquareSumOperatorPrecedence {lowerThan: MultiplicationPrecedencehigherThan: AdditionPrecedenceassociativity: leftassignment: false}
infix operator ◉: SquareSumOperatorPrecedence
Image for post
Image for post
custom infix operator

Where to go from here?

Image for post
Image for post
Example from apple docs
Image for post
Image for post

If you enjoyed reading this post, please share and give some clapps so others can find it 👏👏👏👏👏 !!!!

Written by

iOS and tvOS developer, dreamer, photographer 🤨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store