Swift - Operator Overloading

I remember the day I first learned about the concept of operator overloading in programming languages (it must have been Rodrigo Jordao showing us some work from his Scala projects). It was quite a shock, I found it to be an extremely powerful mechanism. I am aware that with great power comes great responsibilities, but it felt good to know that it was actually possible to overload an operator. Having worked with the languages Java, ABAP, PHP and Objective-C in my career, I didn't really have to chance to try out operator overloading. That is until now!

For those of you who might not be familiar with operator overloading, here is a link: https://en.wikipedia.org/wiki/Operator_overloading

I have recently started working with Swift and in my latest project it did make sense to overload the '-' (subtraction) operator. I wanted to subtract one array from another. Here is how it looked:

extension Array where Element: Equatable {
    
    func minus(listToSubtract: [Element]) -> Array {
        return self.filter { !listToSubtract.contains($0) }
    }
}

Now that the Array class knows how to subtract another array from itself, we can now overload the operator:

func -(left: [User], right: [User]) -> [User] {
    return left.minus(right)
}

Finally, this is how it is being used:

private var onlineUsers: [User]
private var usersThatAreInACallRightNow: [User]

let availableUsers = onlineUsers - usersThatAreInACallRightNow

The array subtraction looks pretty simple and powerful.

One thing to note: After some research, I have learned that the Set data type in Swift does offer this functionality. So, it doesn't really make sense to put this into Array but I must say it felt really good to have the power to overload an operator. This might not have been the right place but maybe there will be a better  use case next time.

Cheers.



Comments

Popular Posts