What is array.append() in Swift?

Overview

The append() method adds single or multiple elements to an array in Swift. It is invoked by an array. We use append(_:) to add a single element. Alternatively, we use append(contentsOf:) if we want to add a multiple.

Syntax

// single element
arr.append(element)
// multiple element
arr.append(contentsOf: [element1, element2...])
Syntax for appending element(s) to an array

Parameters

element: This is the single element we want to append to the arr array.

[element1, element2,...]: This is an array of elements we want to append to the arr array.

Return value

A new array with newly appended elements is returned.

Code example

// create an array
var languages = ["Java", "C++", "Python"]
// append a single element
languages.append("Perl")
// append multiple elements
languages.append(contentsOf: ["Ruby", "Swift"])
// print array values
for lang in languages{
print(lang)
}

Explanation

  • Line 2: We create an array called languages.
  • Line 5: We append a single element to the array.
  • Line 8: Two elements are appended to our array.
  • Line 11: The for-in loop prints each element of the array.

Free Resources