1

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"]
1

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Simpler for loop: for str in ["e","f","g","h"].reversed() { array.insert(str, at: 0) }.

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.