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 trialDevin Tripp
3,826 PointsGenerics in swift
Im really lost and don't knonw what to do I can see how it works in my head but there is so many rules and regulations in swift that stops me from doing the what you want. Someone needs to explain why in the firstplace i cannot just do numberOfItems-- i feel like i could do this in any other language that I know I tried to use a for loop first and that also gave me an errror with numberOfItems. this cod should still work though I don't get it
func duplicate<T>(_ item: T,_ numberOfItems: Int) -> Array<T> {
let array: [T]
var items = numberOfItems
while( items > 0){
array.append(item)
items = items - 1
}
return array
}
1 Answer
Damien Watson
27,419 PointsYou can't do numberOfItems-- because they removed it in Swift, you could use numberOfItems = numberOfItems - 1
I find the for loop to be cleaner. Posting the answer again here so anyone coming across this may be helped.
func duplicate<T>(item:T, numberOfTimes:Int) -> Array<T> {
var newArray: [T] = []
for i in 0..<numberOfTimes {
newArray.append(item)
}
return newArray
}