0

I'm a very beginner at Swift, so this question might be silly.

I want to have a function, where an empty array is created with the same type as an incoming parameter.
I tried something like below, but none of it works.

private func doSomething<T>(source: [T]) {
    var result = [source]
    var result = [source]()
    var result = [type(of:source)]()
    var result: type(of:source) = Array()
}

I see an option to do like this:

private func shuffle<T>(source: [T]) {
    var result = source
    result = []
}

But is there a better way to achieve what I want?

2 Answers 2

4

simply:

var result = [T]()

or

var result: [T] = []
Sign up to request clarification or add additional context in comments.

Comments

2

You can do this:

private func shuffle<T>(source: [T]) {
    var result: [T] = []
    //do something with your result (being an empty array at this point)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.