Sling Academy
Home/Swift/Swift: How to append elements to an array

Swift: How to append elements to an array

Last updated: April 17, 2023

Using the append(_:) method

Appending elements to an array means adding new elements at the end of the array. You can do that in Swift by using the append(_:) method. Note that this method changes the original array and does not return anything.

Example:

var words = ["Sling", "Academy"]
words.append("Swift")
print("words: \(words)")

Output:

words: ["Sling", "Academy", "Swift"]

You can also use the append(_:) method to append another array to a given array like so:

var arr1 = [1, 2, 3]
var arr2 = [4, 5, 6]

arr1.append(contentsOf: arr2)
print(arr1)

Output:

[1, 2, 3, 4, 5, 6]

Note that the second array must have the same data type as the first array.

Using the += operator

An alternative option for appending elements to an existing Swift array is to use the += operator.

Example:

var animals = ["dog", "cat", "bird", "fish"]

// append a single element
animals += ["horse"]

// append an array/multiple elements
animals += ["horse", "cow", "pig"]
print(animals)

Output:

["dog", "cat", "bird", "fish", "horse", "horse", "cow", "pig"]

This approach and the previous one are both convenient and intuitive. Just choose the one you like to go with. This tutorial ends here. Happy coding and have a nice day!

Next Article: Working with the insert() method in Swift

Previous Article: Swift: How to find the length of a given array

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)