Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialChris Hinton
Courses Plus Student 12,588 PointsI 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?
Thanks.
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
Treehouse TeacherHi, 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!
Chris Hinton
Courses Plus Student 12,588 PointsChris Hinton
Courses Plus Student 12,588 PointsThanks Jennifer, that makes sense.