Trung Nguyen
Trung Nguyen

Reputation: 138

How to insert value in array by increasing index in Swift?

I have an array like this:

var Array = ["a","b","c","d"]

How can i use for() loop to insert new values to it, the index of value start from index 0 and it +1 each time i insert new value.

For example

Array.insert("e", at: 0) //["e","a","b","c","d"]
Array.insert("f", at: ???) //["e","f","a","b","c","d"]

Upvotes: 1

Views: 438

Answers (1)

RajeshKumar R
RajeshKumar R

Reputation: 15758

You can insert another array at 0th index using insert(contentsOf:at:)

var Array = ["a","b","c","d"]

Array.insert(contentsOf: ["e","f","g","h"], at: 0) //["e", "f", "g", "h", "a", "b", "c", "d"]

If you want to use for loop then you can use this

for (index,str) in ["e","f","g","h"].enumerated()
{
   Array.insert(str, at: index)
}

Upvotes: 1

Related Questions