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

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

Jhoan Arango
Jhoan Arango
14,575 Points

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