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 elementarr.append(element)// multiple elementarr.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 arrayvar languages = ["Java", "C++", "Python"]// append a single elementlanguages.append("Perl")// append multiple elementslanguages.append(contentsOf: ["Ruby", "Swift"])// print array valuesfor 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-inloop prints each element of the array.