What is array.insert() in Swift?
Overview
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:).
Syntax
// single elementarray.insert(element, at: index)// multiple elementsarray.insert(contentsOf:[element1, element2...], at : index])
Syntax to insert elements to an array in Swift
Parameters
-
element: We want to insert this element into thearrarray. -
[element1, element2...]: These are the elements we want to insert toarrsimultaneously. -
index: This is the index position where we want to make the insertion toarr.
Return value
The value returned is the arr array with the element(s) that are inserted.
Code example
// 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)}
Explanation
- Line 2: We create an array called
languages. - Line 5: We insert a single element to the array at index 2.
- Line 8: We insert multiple elements at index 1 of the array.
- Line 11: We use the
for-inloop to print each element of the array that now contains the inserted values.