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

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