OneBite.Dev - Coding blog in a bite size

Add New Item In Array In Swift

Code snippet for how to Add New Item In Array In Swift with sample and detail explanation

When developing an application in Swift, a common task that you might have to perform is adding a new item into an array. This article will guide you through the process involved in adding a new item to an array in Swift programming language.

Code snippet for Adding a New Item to an Array in Swift

Before we begin, let’s create a base array for our demonstration:

var array = [“Apple”, “Banana”, “Cherry”]

Here, we have an array with three items. To add a new item to this array, use the append() function, like so:

array.append(“Orange”)

After running the above code, if you print your array, you would find the new item at the end of the array:

print(array)

The output of this code would be:

[“Apple”, “Banana”, “Cherry”, “Orange”]

Code Explanation for Adding a New Item to an Array in Swift

The task of adding a new item into an array in Swift is simple with the help of the built-in function append(). This function adds a new element to the end of the array.

Let’s dissect the code:

  1. We start by declaring a variable array with three strings:
var array = [“Apple”, “Banana”, “Cherry”]
  1. Then we use the append() function on our array to add a new item:
array.append(“Orange”)

The append() function takes in one argument – the item you want to add. In our case, we are adding a new string: “Orange”.

  1. Finally, we print the array to see the final output:
print(array)

After using the append() function, the new item is added to the end of our array. Thus, when we print out our array, it now contains four items: “Apple”, “Banana”, “Cherry”, and the newly added “Orange”.

This demonstrates how you can easily add a new item to an array in Swift. It’s worth noting that the append() function works not just for strings, but for items of any data type as long as the array is of the same data type.

swift