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 trialSebastian Lofaro
Front End Web Development Techdegree Graduate 29,101 PointsCode Challenge
I am unable to solve the code challenge. Does anyone have any ideas?
5 Answers
luke jones
8,915 PointsI done it like so:
func duplicate<T>(item: T, numberOfTimes: Int) -> [T] {
var arrayOfT = [T]()
for index in 0..<numberOfTimes {
arrayOfT.append(item)
}
return arrayOfT
}
duplicate(item: 1, numberOfTimes: 4)
But i feel like there might a slightly cleaner way to do it
James J. McCombie
Python Web Development Techdegree Graduate 21,199 PointsJust posting this as an alternative to the answer already supplied...
func duplicate<T>(item: T, numberOfTimes: Int) -> [T] {
return Array(repeating: item, count: numberOfTimes)
}
Xavier D
Courses Plus Student 5,840 Points...did mine with repeat while...
func duplicate<T>(item:T,numberOfTimes:Int)->[T]
{
var repeatWhile=0;var
returnArray:[T]=[]
repeat{returnArray.append(item);repeatWhile+=1}while repeatWhile<(numberOfTimes)
return returnArray
}
duplicate(item: 1, numberOfTimes: 4)
kols
27,007 PointsWell, this is definitely not the cleanest way to solve this (I prefer James J. McCombie's answer — a more elegant / simple solution ); however, this answer does pass, so I'm including below simply for reference in case someone gets stuck on this one:
func duplicate<T>(item: T, numberOfTimes: Int) -> [T] {
var myArray: [T] = []
var counter = numberOfTimes
repeat {
myArray.append(item)
counter -= 1
} while counter > 0
return myArray
}
Joey Liu
3,982 PointsI don't understand why error pop up and said as below: Binary operator '..<' cannot be applied to operands of type 'Int' and 'T'
func duplicate<T>(item: T, numberOfTimes: T) -> [T] { var number:[T] = [] for index in 0..<numberOfTimes { array.append(item) } return array }