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 trialNIKOLA RUSEV
5,293 Pointssecond chalenge??
i try to solve second chalenge but i cant. and i find the code that pass in comunity but i still have some confusions.
- every func that will return a square of some int or double will be return also int or double and requarement in chalenge was (T)->U which means T and U should be defferent type
so this func have no sense. func map<T, U>(array: [T], transformation: (T) -> U) -> [U] { var newArray = U for values in array{ newArray.append(transformation(values)) }
return newArray
}
is there something that i missed??
2 Answers
Xavier D
Courses Plus Student 5,840 Pointsused a while instead of for
func map<T,U>(array:[T],transformation:(T)->U)->[U]
{
var repeatwhile=0;var returnArray:[U]=[]
repeat{returnArray.append((transformation(array[repeatwhile])))
repeatwhile+=1}while repeatwhile<array.count
return returnArray
}
func squaring(_ int:Int)->Int{let squared=int*int;return squared}
map(array: [1,2,3,4,5], transformation: squaring)
NIKOLA RUSEV
5,293 Pointsthanks a lot Claire
Claire Worrmald
6,442 PointsClaire Worrmald
6,442 PointsThe two generic types are T and U, they can be any type and the same if you want but I believe they were trying to make you use different ones to prove a point that you can have as many type parameters as you wish. What they were trying to show you is the flexibility of generics, so rather having to change the map function to cater for every type you can pass in any closure/function that conforms to transformation parameter and it will produce the required result. Here is an example of a function returning square numbers that are of type Double and another one summing the values. Its a bit of a confusing question but hopefully I've helped lift some of the mystery behind it.
Its a weird one to wrap your head around, I could be wrong but I believe this challenge is actually mirroring the map closure that Apple provides which I have included below as a reference.
Hopefully I haven't confused you :)