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 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

Mikis Woodwinter
Mikis Woodwinter
44,941 Points

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?