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 Generic Functions

My code works in playgrounds but i don't know what its asking for in treehouse

So i have tested that this code works. It does the requested objective, but it doesn't work in the treehouse compiler, it tells me to make sure im using the correct variable names, And I'm pretty sure I am.

generics.swift
func duplicate<T>(_ item: T,_ numberOfItems: Int) -> Array<T> {
    var items = numberOfItems
    var newArray: [T] = []
    while( items > 0){
        newArray.append(item)
        items = items - 1
    }
    return newArray
}
Charles Kenney
Charles Kenney
15,604 Points

Not an answer...

That's really odd. Your code checks out. Compilers fault?

Anyhow, this is the code I used and got a pass with. No conceptual differences from yours, other than reverse iteration (which really isn't the norm).

func duplicate<T>(item: T, numberOfTimes: Int) -> Array<T> {
    var result = [T]()
    var counter: Int = 0
    while counter < numberOfTimes {
        result.append(item)
        counter += 1
    }
    return result
}

1 Answer

Damien Watson
Damien Watson
27,419 Points

Hi Devin,

You are setting the item to the number of items, which means you're storing the number into the array instead of the object. Also you don't need to redefine it as its already passed in as a variable.

This code works and is a bit simpler:

func duplicate<T>(item:T, numberOfTimes:Int) -> Array<T> {
  var newArray: [T] = []
  for i in 0..<numberOfTimes {
    newArray.append(item)
  }
  return newArray
}
Damien Watson
Damien Watson
27,419 Points

Also, passing in playgrounds just means it doesn't have compiler errors, doesn't mean that it meets the challenge criteria. :)