How to insert elements anywhere in an array in Swift
Overview
Elements can be inserted at any position into an array, using the insert(contentsOf:at:) method. All we need to do is specify the elements we want to insert, along with the index position of where the insertion should begin.
Syntax
arr.insert(contentsOf: elements, at: index)
Parameters
elements: These are the elements that we want to insert into the array arr.
index: This is the index position at which we want to start the insertion.
Return value
The value returned is a new array with the specified elements inserted at the index position index.
Code example
// create arraysvar arr1 = [1, 3, 4]var arr2 = ["a", "b", "g"]var arr3 = ["Amazon", "Meta"]// insert elements to any positionarr1.insert(contentsOf: [100, 200], at: 3)arr2.insert(contentsOf: ["c", "d", "e", "f"], at : 2)arr3.insert(contentsOf: ["Google", "Netflix", "Apple"], at : 0)// print modified arraysprint(arr1)print(arr2)print(arr3)
Code explanation
- Lines 2–4: We create some arrays.
- Lines 7–9: We insert some elements into the arrays we created by specifying the position at which they should be inserted.
- Lines 12–14: We print the modified arrays.