Swift .append()

Christine_Yang's avatar
Published Oct 11, 2022Updated May 26, 2023

The .append() method will add an element to the end of an array. It 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.append(element)

arrayName.append(contentsOf: [element1, element2, ...])

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

Example

var topBabyNames = ["Sophia", "Liam"]
topBabyNames.append("Riley")
print(topBabyNames)
topBabyNames.append(contentsOf: ["Olivia", "Noah"])
print(topBabyNames)

This will output:

["Sophia", "Liam", "Riley"]
["Sophia", "Liam", "Riley", "Olivia", "Noah"]

Note: Big-O of this method is O(1).

All contributors

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