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 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,199 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 }