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!