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

don't really catch the clue

don't really catch the clue

generics.swift
func duplicate<T>(item: T, numberOftimes: Int) -> [T] {

    var array = [item]
    let item = 1
    let numberOftimes = 4


    for item in 1...numberOftimes {

      array.append(item)

        return array as! [T]
}

    return [T]()
}

2 Answers

Jhoan Arango
Jhoan Arango
14,575 Points

Hello John:

Generics are amazing and one of the best things about swift. They may be hard to understand at first, but once you get the hang of it you'll love them as I do.

You were pretty close in your attempt to pass the challenge, but we can improve your code by doing something a bit more simple. Instead of using a "For in" we can use "while" loop. You did have the idea on using a loop, so that's a good start.

The good thing about the while loop is that you can make it work until it meets a condition. In this case we want to meet the condition of numberOfTimes.

Here is how It would look.

func duplicate<T>(item: T, numbersOfTimes: Int) -> [T] {

   // Array of items ( generic items )
    var items = [T]() 

  // Append item till condition is met
    while numbersOfTimes != items.count {
        items.append(item) 
    }

    // Then we simply return the items
    return items

}

If you need more help please let me know..

Also remember to select your best answers to help others know which answers helped you solve and understand your problems.

Good luck

thks Jhoan