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.
arr.insert(contentsOf: elements, at: index)
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.
The value returned is a new array with the specified elements inserted at the index position index
.
// 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)