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

Generics in swift

Im really lost and don't knonw what to do I can see how it works in my head but there is so many rules and regulations in swift that stops me from doing the what you want. Someone needs to explain why in the firstplace i cannot just do numberOfItems-- i feel like i could do this in any other language that I know I tried to use a for loop first and that also gave me an errror with numberOfItems. this cod should still work though I don't get it

generics.swift
func duplicate<T>(_ item: T,_ numberOfItems: Int) -> Array<T> {
    let array: [T]
    var items = numberOfItems
    while( items > 0){
        array.append(item)
        items = items - 1
    }
    return array
}

1 Answer

Damien Watson
Damien Watson
27,419 Points

You can't do numberOfItems-- because they removed it in Swift, you could use numberOfItems = numberOfItems - 1

I find the for loop to be cleaner. Posting the answer again here so anyone coming across this may be helped.

func duplicate<T>(item:T, numberOfTimes:Int) -> Array<T> {
  var newArray: [T] = []
  for i in 0..<numberOfTimes {
    newArray.append(item)
  }
  return newArray
}