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

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