Swift .insert()

Christine_Yang's avatar
Published Oct 11, 2022
Contribute to Docs

The .insert() method will add an element to a desired position of an array. When an element is added at the specified index, all later ones are pushed to the right in order to make room. This method allows for single and multiple element additions.

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours

Syntax

arrayName.insert(element, at: index)

arrayName.insert(contentsOf: [element1, element2, ...], at: index)

The method is called on an array instance at a specific index, and one or more elements can be added using the contentsOf: parameter.

Example

var topBabyNames = ["Liam", "Olivia", "Emma", "Elijah"]
topBabyNames.insert("Noah", at: 2)
print(topBabyNames)
topBabyNames.insert(contentsOf: ["Oliver", "Charlotte"], at: 4)
print(topBabyNames)

This will output:

["Liam", "Olivia", "Noah", "Emma", "Elijah"]
["Liam", "Olivia", "Noah", "Emma", "Oliver", "Charlotte", "Elijah"]

All contributors

Contribute to Docs

Learn Swift on Codecademy

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours