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

Aananya Vyas
Aananya Vyas
20,157 Points

why is the 'item' not being assigned to arr[i] ?

in xcode it says 'variable 'arr' passed by refrence before being initialised '

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

    for var i in 0...numberOfTimes-1 {
        arr[i] = item
        i += 1
    }

return arr
}

1 Answer

Hello,

There are different ways on how to achieve this. You were close by using the for in loop.

Here is one way of doing it with the for in loop.

func duplicate<T>(item: T, numberOfTimes: Int) -> [T] {
    var items = [T]()

// for in loop and range.    
    for _ in 0...numberOfTimes - 1 {
        items.append(item)
    }

    return items
}

duplicate(item: "Test", numberOfTimes: 5)

Altho this is a good implementation of it, I favor the while loop for this task and the reason is that I think it's more readable. Also, the usage of the for in loop is more favorable to iterate through a sequence such as a range of numbers, and items in an array.

func duplicate<T>(item: T, numberOfTimes: Int) -> [T] {
    var items = [T]() // Empty Array

// while loop
   while items.count != numberOfTimes {
        items.append(item)
   }

    return items 
}

duplicate(item: "Test", numberOfTimes: 5)

Good luck