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

Jiri Janecek
Jiri Janecek
6,443 Points

Any idea what's wrong with this?

Hi all. This is the task: "Write a function named duplicate with a single generic type parameter T. The function takes two arguments, item of type T, and numberOfTimes of type Int, and returns an array of type T. The function simply creates an array containing the element duplicated by the number of times specified. For example, calling duplicate(item: 1, numberOfTimes: 4) returns [1, 1, 1, 1]"

Any idea what's wrong with my code? The declaration of this function is fine in Xcode (= no errors) but when I try to actually use it, that's when I get an error. Thanks

generics.swift
func duplicate<T>(item: T, numberOfTimes: Int) -> [T]{
    var array: [T] = []

    for i in 0..<numberOfTimes {
        array[i] = item
    }

    return array
}

1 Answer

Ian Billings
PLUS
Ian Billings
Courses Plus Student 7,494 Points

Hi Jiri,

The problem is in your for loop you are attempting to access an array index that doesn’t exist. So it errors instead of adding the item to the array. You need to change it to: array.append(item)

Ian