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

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

Thank you sir! :)