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