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

swift 3 generics 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.

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

var larger: T = 0 as! T

for var i in 0...`in`.count-1 {
    if `in`[i] > larger {
        larger = `in`[i]
        i += 1
    }
}

return larger

}

works in playground, doesn't work in challenge. Challenge give no details, error is "Bummer"

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


    var larger: T = 0 as! T

    for var i in 0...`in`.count-1 {
        if `in`[i] > larger {
            larger = `in`[i]
            i += 1
        }
    }

    return larger


}

largest(in: [1,2,3])
Jonathan Sweeney
Jonathan Sweeney
14,559 Points

Hey realize this is late. I think I found a couple issues as to why your solution didn't pass the coding challenge.

  1. Your solution handles only Integer values, which I believe defeats the purpose of using a generic type. Instead of initializing var larger: T = 0 as! T (0 is of data type Int), try setting it to the value at index 0 in the array.
  2. Silly, but I wonder if your solution may have also been tripped up by not giving the argument an external name of 'in'.

Below is my solution. Hope this helps someone down the road!

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

    if array.isEmpty { return nil }

    var largestValue = array[0]

    for item in array {
        if item > largestValue {
            largestValue = item
        }
    }

    return largestValue
}

largest(in: [1,2,3])      // 3
largest(in: [3,2,1])     // 3 
largest(in: ["a", "abba", "A", "z"])  // z
largest(in: [1.0, -2.0, 3.333])  //3.333