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 Class Based Type Constraints

Ayo Omotosho
Ayo Omotosho
4,855 Points

Comparable conformance task

"In the editor, define a function, named largest, with a generic type parameter, T. The function takes an array of type T as its first argument. Give this argument an external name of in. The return type of the function is optional T. Given an array the function should return the largest value in the array. For example, calling largest(in: [1,2,3]) should return 3. To make this work, you'll need to constrain the generic type T to conform to Comparable."

Some help with the question above will be highly appreciated. My answer runs in Xcode but doesn't get me through this challenge in the Generics Track, i'm pretty sure it's because i'm not using the "==" equator the right way. Thanks.

3 Answers

Bertram Srugies
Bertram Srugies
4,704 Points

I used the following solution

func largest<T: Comparable>(in array: [T]) -> T? {
return array.max()
Xavier D
Xavier D
Courses Plus Student 5,840 Points

...didn't use any variables...

func LargesT<T:Comparable>(in l1I:[T])->T?{return l1I.sorted()[((l1I.sorted().count)-1)]}
Alex Koumparos
Alex Koumparos
Python Development Techdegree Student 36,862 Points

Without seeing your code it's difficult to diagnose exactly where the problem is. However, the fact that you are asking about the == operator is a clue. To solve this we don't need to be able to determine whether any element in the array is equal to any other, just whether it is larger, so the only operator we need to compare the elements is >.

In the most obvious solution, you would have a temporary largestSoFar variable (of type T) and as you iterate through the elements in the array you check if the new element is larger than the largest so far, and if so update the temp variable. At the end you return the value in the temp variable.

I don't imagine that Treehouse is keen on posting full solutions, so I haven't, but I'm happy to provide snippets if you are unsure of anything.