Kodeco Forums

Overloading Custom Operators in Swift

In this Swift tutorial, you'll learn how to create custom operators, overload existing operators, and set operator precedence.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/650-overloading-custom-operators-in-swift

Great tutorial, especially the precedence group part that I just discovered :slight_smile:

I just want to clarify a point, when you introduce protocol operators, your first paragraph is :

Some protocols are required members of protocols. For example, a type that conforms to Equatable must implement the == operator. Similarly, a type that conforms to Comparable must implement at least < (and optionally >, >=, and <=)

You should note that Comparable protocol needs also to implement the == operator, since according to Comparable protocol reference, Comparable extends Equatable.

Only the < operator have to be implemented because, as written in the Comparable protocol reference, default implementation exists for the others :

Because default implementations of the remainder of the relational operators are provided by the standard library, you’ll be able to use !=, >, <=, and >= with instances of your type without any further code.

All these operators can be obtained by the two needed :

A != B    <=>      !(A == B)
A >  B    <=>       B < A
A <= B    <=>      (A < B) || (A == B) 
A >= B    <=>      (B < A) || (A == B)

Sorry for not replying sooner, I’ve been really backed up and haven’t had a chance to check in. You’re definitely correct, and I’ll make the appropriate changes in a couple hours to fix that error. Thanks for pointing it out!

This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]