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

Everton Carneiro
Everton Carneiro
15,994 Points

error: '([T]) -> U' is not convertible to '(T)

First time working with generics in swift, couldn't figure out how to fix it. I understand what the error is about but couldn't find the right syntax to express what I'm trying to do. How can I pass an array to transformation if the parameter inside is a type T and not an array of T? I came up with this solution:

func map<T, U>(array: T, transformation: (T) -> [U]) -> [U] {

    return transformation(array)
}

func squaredElements(array: [Int]) -> [Int]{
    var squaredArr = [Int]()
    for i in 0...array.count-1{
        squaredArr.append(array[i]*array[i])
    }
    return squaredArr
}

var arr = [1,2,3,4,5]


map(array: arr, transformation: squaredElements)

Does exactly what is asked to the quiz, but in other way. But doesn't solve the question as is asked.

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

    return transformation(array)
}


//func squaredElements(array: [Int]) -> [Int]{
//    var squaredArr = [Int]()
//    for i in 0...array.count-1{
//        squaredArr.append(array[i]*array[i])
//    }
//    return squaredArr
//}

2 Answers

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

Pretty close. It looks like you missed that you are supposed to loop over the array argument and call transformation on each of the elements, then return the transformed items.

Hope this helps!

Everton Carneiro
Everton Carneiro
15,994 Points

Thank you, Caleb. This was very helpful! I don't know why I didn't though about looping inside the generic function!

func map<T, U>(array: [T], transformation: (T) -> U) -> [U] {
    var newArray = [U]()
    for element in array{
        newArray.append(transformation(element))
    }
    return newArray
}

Now it's correct! Thank you again!