Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Generics in Swift Generic Functions, Parameters and Constraints Writing Generic Functions

5 Answers

luke jones
luke jones
8,915 Points

I 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
James J. McCombie
Python Web Development Techdegree Graduate 21,137 Points

Just 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
PLUS
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)

Well, this is definitely not the cleanest way to solve this (I prefer James J. McCombie's answer — a more elegant / simple solution :thumbsup:); 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
Joey Liu
3,982 Points

I 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 }