O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Inserting a value into an array

We can insert a value into an array by using the insert method. The insert method will move all the items up one spot, starting at the specified index, to make room for the new element, and then insert the value into the specified index. The following example shows how to use this method to insert a new value into an array:

var arrayOne = [1,2,3,4,5] 
arrayOne.insert(10, at: 3) //arrayOne now contains 1, 2,3, 10, 4 and 5 
You cannot insert a value that is outside the current range of the array. Attempting to do so will throw an Index out of range exception. For example, in the preceding code, if we attempt to insert a new integer at index 10, we will receive an Index out of range exception error because arrayOne ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required