2

I am new to Swift and I am trying to copy one array to another.

What I am trying to do is copy the content of Array1 to Array2. But the Array2 content should have contents from a particular index. For example:

Array1 have 100 elements ie. index from 0 to 99. In Array2 I want to copy say, elements from index 25 to last element(ie. 99).

How can I do it. I try searching the problem but did not get the solution.

Please help. Thanks in advance.

2 Answers 2

9

If you have this array:

var x = [1, 2, 3, 4, 5]

and you want to obtain a copy from the 3rd element up to the end:

var y = x[2..<x.count]

y will contain [3, 4, 5]

Note that arrays are value types, so they are copied by value - every time you assign an array to another variable (or pass to a function), a copy of it is actually assigned/passed. So you don't have to do anything more to obtain a copy.

Sign up to request clarification or add additional context in comments.

2 Comments

if the start index is a variable
just use the variable instead of the literal: var index = 2; var y = x[index..<x.count]
7

You can use Range subscription like this:

let array = [1,2,3,4, .....]
let sliced = array[25...99]

Note that, type of sliced here is Slice<Int>, it has almost the same interface as Array, so you can use that as Array as is.

If you do want real Array, do Array(array[25...99])

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.