Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift Array insert()
In this tutorial, we will learn about the Swift Array insert() method with the help of examples.
The insert() method inserts an element to the array at the specified index.
Example
// create a list of vowels
var vowel = ["a", "e", "i", "u"]
// 'o' is inserted at index 3 (4th position)
vowel.insert("o", at: 3)
print(vowel)
// Output: ["a", "e", "i", "o", "u"]
insert() Syntax
The syntax of the array insert() method is:
array.insert(newElement, at: index)
Here, array is an object of the Array class.
insert() Parameters
The insert() method takes two parameters:
- newElement - element to be inserted to array
- index - the index where the element needs to be inserted
insert() Return Value
The insert() method doesn't return any value. It only updates the current array.
Example 1: Swift Array insert()
// create a array of prime numbers
var prime = [2, 3, 5, 7]
// insert 11 at index 4
prime.insert(11, at: 4)
print(prime)
Output
[2, 3, 5, 7, 11]
Example 2: Using insert() With startIndex and endIndex
// create a array of even
var even = [4, 6, 8]
// insert 2 at the starting index
even.insert(2, at: even.startIndex)
// insert 10 at the end
even.insert(10, at: even.endIndex)
print(even)
Output
[2, 4, 6, 8, 10]
Here,
startIndex- inserts element at the starting index i.e. index 0endIndex- inserts element at the end of the array.
Did you find this article helpful?