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

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

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
}
func largest<T:Comparable>(in array: [T]) -> T? {
    return array.max()
}

Check this out!