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.


Toby Morgan
.a{fill-rule:evenodd;}techdegree seal-36
Toby Morgan
iOS Development Techdegree Graduate 23,133 Points

Clarifying my Understanding (and to help others?) [Intermediate Swift Course, Method Dispatch in a Protocol Extension]

Took me while to really get at what was being demonstrated here. But now that I think I understand the concepts, does the following make sense? (apologies for the length of the question)

My understanding:

  • fullName() is part of the original PersonType protocol (so I'll call it a "first-class" method requirement)
  • greeting() is part of the extension to the PersonType protocol (so I'll call it a "second-class" method requirement)
  • this means they have different behaviors under certain circumstances

When it matters:

  • if you create a variable of the protocol type and assign it an instance of a concrete class that implements the protocol [e.g. let anotherUser: PersonType = User(....]
  • when you have a heterogeneous collection that has upcast itself to the protocol type to accomodate mixed concrete types that implement that protocol [e.g. let people = [someUser, anotherUser, someFriend] ]

What happens:

  • if it is a "first-class" method requirement (part of the original protocol) when you call the method Swift does a kind of implicit downcasting and calls the implementation on the concrete type
  • if it is a "second-class" method requirement (part of an extension to the original protocol) then no magical in-line downcasting occurs and the default implementation in the protocol extension is called

So my question is in two parts:

  • Is what I've said above correct?
  • Couldn't we just avoid this nuance by always explicitly downcasting to its concrete type before calling any methods? Meaning is there a benefit to this Swift behavior, or is it just a quirk of Swift that needed to be called out to avoid pitfalls?