Triple equality in Swift

David Gavilan
2 min readFeb 26, 2020

--

Values vs References

Structs in Swift are copied by value, while classes are copied by reference. If we want to check if the reference of an object is the same, we can use the triple equality operator. From Apple’s book “The Swift Programming Language”,

Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance.

I’ve put here a few examples that you can copy-paste into a Swift Playground to understand what the above means when using comparison operators:

Defining Equality

We can define an equality function if we want to check for the equality of the Bread and Cheese values from the examples above,

If we want to be able to pass a “cheese” to the “contains” or “indexOf” methods of an array, we have to conform to the Equatable protocol. Having the equality function alone doesn’t work. This will work,

Happy coding!

Relevant StackOverflow questions:

Originally published at http://endavid.com.

--

--

David Gavilan

Ph.D. Graphics Engineer at Metail. Worked on several graphics engines in the past (Fox Engine, Disney Infinity, mobile VR, server-side rendering).