Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
insert
swift
communitycreator

What is array.insert() in Swift?

Theodore Kelechukwu Onyejiaku

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 element
array.insert(element, at: index)
// multiple elements
array.insert(contentsOf:[element1, element2...], at : index])
Syntax to insert elements to an array in Swift

Parameters

  • 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.

Return value

The value returned is the arr array with the element(s) that are inserted.

Code example

// create an array
var languages = ["Java", "C++", "Python"]

// insert single element
languages.insert("Swift", at: 2) // 3rd position

// insert multiple elements
languages.insert(contentsOf: ["C", "Perl"], at :1) // 2nd position

// print new array
for lang in languages{
  print(lang)
}
Inserting elements to an array in Swift

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-in loop to print each element of the array that now contains the inserted values.

RELATED TAGS

array
insert
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring