Swift - Inserting Elements into an Array


To insert an element into an array at a particular index, use the insert() function:

var OSes :[String]  = ["iOS", "Android", "Windows"]
//inserts a new element into the array at index 2
OSes.insert("BlackBerry", atIndex: 2)

Here, in the preceding function call for insert() , you specify the parameter name - atIndex.

This is known as an external parameter name and is usually needed if the creator of this function dictates that it needs to be specified.

You can insert an element using an index up to the array's size.

You can insert an element to the back of the array using the following:

OSes.insert("Tizen", atIndex: 4)

The following statement will result in a runtime failure, as the index of 5 is out of the range (maximum accessible index is 4):

//index out of range
OSes.insert("Tizen", atIndex: 5)

Related Topic