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

Jason Wayne
Jason Wayne
11,688 Points

Is there something wrong with the Generic Code Challenge (asking to write a duplicate with a single generic type.....) ?

We were asked to write a function named "duplicate" with a single generic type parameter T. The function takes 2 arguments, item of type T and numberOfTime of type Int, which returns an array of type T.

Below is my function, tested it on Playground, seems to be producing the output that the question is asking. Please do correct me if I'm wrong. Thanks!

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

    var theItemArray = [T]()

    var count = 0
    while count < numberOfTimes {

        theItemArray.append(item)
        count += 1
    }
    return theItemArray
}

var a = 5

let duplicateValue = duplicate(item: &a, numberOfTimes: 10)

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,546 Points

Hey Jason,

For this challenge, there are just two things that are preventing your code from passing.

  1. In the function declaration, you added inout for the 'item' argument. (Delete that).
  2. Remove the ampersand (&) from the argument in the function call.

Fix that up and the rest is good to go. :)

Keep Coding! :dizzy:

Jason Wayne
Jason Wayne
11,688 Points

Jason Anders - Thanks! It worked. I just dropped the inout.