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 CSS Background Blend Modes Challenge

I think there is an error in this course

I wrote a code that works, but I can not get it to compile the way it's asking me to. Is this an error, or am I doing it wrong?

In the editor define a function named map with two generic type parameters, T and U. The function takes two arguments - array of type [T], and transformation of type (T) -> U. The function returns an array of type U. The goal of the function is to apply the transformation operation on the array passed in as argument to return a new array containing the values transformed. For example given the array [1,2,3,4,5] as first argument, and a square function as the transformation argument, the result should be [1, 4, 9, 16, 25].

generics.swift
func map<T, U>(array: T, transformation: (T) -> U ) -> [U] {
    return [transformation(array)]
    }


func squareArray(_ value: [Int]) -> [Int] {

    var newArray: [Int] = []

    for n in value {

        newArray.append(n * n)
    }

   return newArray
}

1 Answer

Adland Lee
Adland Lee
5,538 Points
func map<T, U>(array: T, transformation: (T) -> U ) -> [U] {
    return [transformation(array)]
    }

Check the function input type for array. This function signature shows array as type T. The task specifically states the array parameter should be [T] which is an array of type T