Swift Program to append an element into an array


In this article, we will learn how to write a swift program to append an element into an array.

An array is used to store elements of same data type in an order whereas a set is used to store distinct elements of same data type without any definite order. Here we use the following methods to append an element into an array −

  • Using append(_:) function

  • Using operator

Method 1: Using append(_:) function

To append an element in the array we uses append( function. The append(_:) function adds a new element at the end of the array.

Syntax

func append(_value:Element)

Here, value represent the element which we want to append.

Algorithm

  • Step 1 − Create an array of string type.

  • Step 2 − Print the original array.

  • Step 3 − Append an element at the end of the specified array using append() function. myColors.append("Yellow")

  • Step 4 − Print the output.

Example

Following Swift program to append an element into an array.

import Foundation
import Glibc

// Creating an array of string type
var myColors = ["blue","Pink","Brown","Orange"]
print("Original array:", myColors)

// Appending an element in the array
myColors.append("Yellow") 
print("Modified array:", myColors)

Output

Original array: ["blue", "Pink", "Brown", "Orange"]
Modified array: ["blue", "Pink", "Brown", "Orange", "Yellow"]

Here in the above code, we have an array of string. Now we use append(_:) function to append an element named Yellow at the end of the array.

Method 2: Using operator

We can also use operator to append an element to an array. This operator appends an element at the end o f the specified array. It can also append multiple elements at the end of the array.

Syntax

Array += [element]

Here, element represent the item which we want to append to the Array.

Algorithm

  • Step 1 − Create an array of string type.

  • Step 2 − Print the original array.

  • Step 3 − Append an element at the end of the specified array using operator. mytable += [40]

  • Step 4 − Print the output.

Example

Following Swift program to append an element into an array.

import Foundation
import Glibc

//Creating an array of integer type
var mytable = [ 10, 15, 20, 25, 30, 35]
print("Original array:", mytable)

//Appending an element in the array
mytable += [40]
print("Modified array:", mytable)

Output

Original array: [10, 15, 20, 25, 30, 35]
Modified array: [10, 15, 20, 25, 30, 35, 40]

Here in the above code, we have an array of integer type. Now we use += operator to append an element(the is 40) at the end of the given array and display the output.

Conclusion

So this is how we can append an element into an array. Here both the methods append the elements at the end of the original array. They does not create new array.

Updated on: 17-Jan-2023

915 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements