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 Generic Functions with Constraints

Will Matthews
Will Matthews
8,127 Points

Why is the return type optional?

Given that we're constraining the type to be comparable, why is the return type optional? Under what circumstances would the returned value be nil?

1 Answer

Brandon Adams
Brandon Adams
10,325 Points

Sometimes the return type can be void because the function handles everything internally. You could compare two things and the function calls another function internally instead of returning a value.

Will Matthews
Will Matthews
8,127 Points

I'm not sure I follow this logic. Even if this function were to call a helper method, control flow would still have to return to the largest function after it was done doing whatever was doing wouldn't it?

I guess where I'm confused is that in any comparable set, there's always going to be a "largest" value. Even if they're all the same, it would be an n-way tie for first, no? So then the nil case would only come up if the items weren't comparable at all, but since we're constraining generic T to be Comparable, aren't we precluding this nil case?