Multiple ways to add an element to an array in Swift with example

This tutorial shows multiple ways to add an element to an array in Swift with examples.

  • Add an element to the end of an array using the append method. [1,2].append(3) returns [1,2,3]
  • Add an element at the index position using the insert method. [11,12].insert(2,0) adds an element at index=0, returns [2,11,12]
  • += operator that adds an element to the end. ["one", "two"]+=["three"]returns ["one", "two", "three"]

An array is a group of elements of the same type. Each element access with an index. The first element starts with index=0, the last element ends with index=length-1.

Element adds to the start, middle, or end of an array.

How to add an element to an array in Swift

There are multiple ways we can add an element either start, end, or index=0.

  • append method

Use the append method to add an element to the end of an array.

Syntax:

mutating func append(\_ newElement: Element)
//Add an element to the end of an array
numbers.append("five")

To add an element or sub-array to an end of an array.

//Add a subarray to the end of an array
numbers.append(contentsOf: ["six", "seven"])

Here is a complete example

import Foundation

var numbers = ["one", "two", "three", "four"]
print(numbers)
//Add an element to the end of an array
numbers.append("five")
print(numbers)
//Add a subarray to the end of an array
numbers.append(contentsOf: ["six", "seven"])
print(numbers)
  • insert method

The insert method adds an element at index position zero.

Syntax:

mutating func insert(
\_ newElement: Element,
at i: Int
)

To add an element to the index of an array.

// add an element to an array index=1
numbers.insert("five",1)

To add an element or sub-array to an end of an array.

// add a subarray to array index=3
numbers.insert(contentsOf: ["six", "seven"],at:3)

Here is a complete example

import Foundation

var numbers = ["one", "two", "three", "four"]
print(numbers)
//Add an element to the end of an array
numbers.insert("five",at:1)
print(numbers)
//Add a subarray to the end of an array
numbers.insert(contentsOf: ["six", "seven"],at:3)
print(numbers)

Output:

["one", "two", "three", "four"]
["one", "five", "two", "three", "four"]
["one", "five", "two", "six", "seven", "three", "four"]
  • use += operator

Another way using the += operator.

It adds single or multiple elements to the end of the array.

Here is an example

import Foundation

var numbers = ["one", "two", "three", "four"]
print(numbers)
//Add an element to the end of an array
numbers += ["five"]
print(numbers)
//Add an subarray to the end of an array
numbers += ["six", "seven"]
print(numbers)

Output:

["one", "two", "three", "four"]
["one", "two", "three", "four", "five"]
["one", "two", "three", "four", "five", "six", "seven"]