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
Darcy Phillips
4,087 Pointsprotocol extension question
Here's a multiple choice question:
protocol SomeProtocol {
func someMethod() -> Int
}
extension SomeProtocol {
func someMethod() -> Int {
return 1
}
}
struct SomeStruct: SomeProtocol {
func someMethod() -> Int {
return 2
}
}
let b: SomeProtocol = SomeStruct()
b.someMethod()
What is the value returned from the someMethod() call
My answer, 1, is apparently wrong. Which I find confusing, cause I thought that this was the exact point of the lesson. Here's a quote from the video, with the type name changed to refer to this example:
"even though this is an instance of [SomeStruct], because the type is specified as the protocol type, it defaults to the implementation provided in the extension, and it ignores the implementation defined in the type."
By that logic the answer should be 1, the implementation in the extension. No?
3 Answers
Greg Kaleka
39,021 PointsHi Darcy,
This is a bit tricky, but here's what's happening:
- The protocol
SomeProtocolrequiressomeMethod(). - The extension provides a default implementation for
someMethod(), which means when conforming toSomeProtocol, you don't need to implementsomeMethod()if you want to simply accept this default implementation - Instead, though, when declaring
SomeStruct, the default implementation was overridden. If the default implementation is overridden, that behavior is what you'll get.
I'm not sure what the quote is referencing - it will depend a bit on what the code was. Hopefully the above makes sense, though!
Cheers
-Greg
Darcy Phillips
4,087 PointsHi Greg, thanks for that- yes, I understand those points.
This multiple choice question goes one step further though (i think?), asking which implementation will be chosen when the variable is specified as the protocol type. The quote is from the video preceding this quiz, which I transcribed.
Shouldn't I properly conclude that, in this case, the protocol's default implementation will be chosen, because "b" is specified as being of type "SomeProtocol"?
Thank you!
Greg Kaleka
39,021 PointsCan you link me to the video in question?
Darcy Phillips
4,087 PointsThe video is "Method Dispatch in a Protocol Extension", in the "Extensions and Protocols" section of the "Intermediate Swift 2" course. The quote is at 5:06 in video.
Thanks!