In Swift, we use the array method insert() to add elements in the middle of an array. For a single element, we can use insert(_:at:), while for multiple elements, we can use insert(contentsOf:at:).
// single elementarray.insert(element, at: index)// multiple elementsarray.insert(contentsOf:[element1, element2...], at : index])
element: We want to insert this element into the arr array.
[element1, element2...]: These are the elements we want to insert to arr simultaneously.
index: This is the index position where we want to make the insertion to arr.
The value returned is the arr array with the element(s) that are inserted.
// create an arrayvar languages = ["Java", "C++", "Python"]// insert single elementlanguages.insert("Swift", at: 2) // 3rd position// insert multiple elementslanguages.insert(contentsOf: ["C", "Perl"], at :1) // 2nd position// print new arrayfor lang in languages{print(lang)}
languages.for-in loop to print each element of the array that now contains the inserted values.