Goltsev Eugene
Goltsev Eugene

Reputation: 3627

Swift init empty array with the same type as another array

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?

Upvotes: 0

Views: 48

Answers (2)

Sulthan
Sulthan

Reputation: 130072

simply:

var result = [T]()

or

var result: [T] = []

Upvotes: 4

Kamil.S
Kamil.S

Reputation: 5543

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)
}

Upvotes: 2

Related Questions