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

Aananya Vyas
Aananya Vyas
20,157 Points

no clue as to why my code wont work!!

it works alright in xcode is there something in the challenge i am missing out? THE QUESTION : 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.

MYCODE: ```func largest<T: Comparable>( in inn: [T] ) -> T? {

var large: T? = 0 as? T


for var i in 0...inn.count-1 {
    if inn[i] > large! {
        large = inn[i]
        i += 1
    }
}

guard let value = large else {fatalError()}
return value

}

largest(in: [1,2,3,4])```

generics.swift
func largest<T: Comparable>( in inn: [T] ) -> T? {


    var large: T? = 0 as? T


    for var i in 0...inn.count-1 {
        if inn[i] > large! {
            large = inn[i]
            i += 1
        }
    }

    guard let value = large else {fatalError()}
    return value


}

largest(in: [1,2,3,4])

2 Answers

Jeff McDivitt
Jeff McDivitt
23,970 Points

This should help you

func largest<T: Comparable>(in array: [T]) -> T? {
    var largest: T?

    if let largestNum = array.max() {
        largest = largestNum
    } else {
        return nil
    }

    return largest
}
Qasa Lee
Qasa Lee
18,915 Points
func largest<T:Comparable>(in array: [T]) -> T? {
    return array.max()
}

Check this out!