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 trial

iOS Generics in Swift Generic Functions, Parameters and Constraints Protocol Based Type Constraints

Will Matthews
Will Matthews
8,127 Points

Why use an extension here?

In the example, we used an extension to add the Equatable conformance to Item. What rationale should we be considering when using an extension versus adding the conformance to the struct itself?

3 Answers

Hi Will,

It's a common convention in Swift to use extensions to break apart the functionality of a class/structure into different sections, usually according to conformance to some protocol(s). It makes things more readable. Still, there's nothing preventing you from not doing things this way.

Will Matthews
Will Matthews
8,127 Points

Gotcha. I think that's what I've been seeing in some of the examples that follow this one too. Makes sense. Thanks!

Jeff McDivitt
Jeff McDivitt
23,970 Points

An extension allows a computed property

Will Matthews
Will Matthews
8,127 Points

We're using a type method in this case, though, not a computed property. As well, a computed property could surely be included in the definition of the object rather than only in an extension, no?

I'm just wondering, was there a specific reason that we added the Equatable-conforming method using an extension rather than just adding it to the object definition, or was it mainly just to get more practice working with extensions? ie. is there some rationale we should be using when choosing between extensions and editing our own objects?