Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Protocols in Swift Creating Flexible Objects Using Protocols Swift's Standard Library Protocols

Chris Hinton
Chris Hinton
Courses Plus Student 12,588 Points

I was able to say "user == anotherUser" by only conforming to Equatable (before implementing the == function). How?

My code is below.

The line user == anotherUser returned true, and if I changed the address in anotherUser it then returned false. So it looks like it was checking equality on all the stored properties. How did that work if I'd never implemented the == function in my struct?


struct User: PrettyPrintable, Equatable {
    let name: String
    let age: Int
    let address: String    

    func description() -> String {
        return "\(name), \(age), \(address)"

    func prettyDescription() -> String {
        return "Name: \(name),\nAge: \(age),\nAddress: \(address)"

let user = User(name: "Chris", age: 41, address: "My Address")
let anotherUser = User(name: "Chris", age: 41, address: "My Address")

user == anotherUser

1 Answer

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi, Chris Hinton ! As I understand it, the Equatable protocol checks through every property to see if the values match by default. The use of the == function is there if you want to customize what you're checking for in some way. I might suggest taking a look at the Apple Developer documentation on the Equatable protocol here.

This excerpt is particularly interesting in this case.

To customize your type’s Equatable conformance, to adopt Equatable in a type that doesn’t meet the criteria listed above, or to extend an existing type to conform to Equatable, implement the equal-to operator (==) as a static method of your type. The standard library provides an implementation for the not-equal-to operator (!=) for any Equatable type, which calls the custom == function and negates its result.

Hope this helps! :sparkles: