What is the removeFirst() method in Swift?

Overview

The removeFirst() method of an array in Swift removes and returns the first element of an array.

Syntax

arr.removeFirst()

Parameters

This method takes no parameters.

Return value

The removed element is returned.

Code example

// create arrays
var numbers = [1, 3, 10, 4]
var techCoys = ["Google", "Amazon", "Netflix"]
var letters = ["a", "b", "c", "d", "e"]
var fruits = ["apple", "mango"]
// remove first elements
let num = numbers.removeFirst()
let tech = techCoys.removeFirst()
let letter = letters.removeFirst()
let fruit = fruits.removeFirst()
// print results
print(num)
print(tech)
print(letter)
print(fruit)
// print arrays again
print("New Arrays: \n")
print(numbers)
print(techCoys)
print(letters)
print(fruits)

Explanation

  • Lines 2-5: We create arrays.
  • Lines 8-11: We use the removeFirst() method to remove the first elements of the arrays that we’ve created. We then store the results in some variables.
  • Lines 14-17: We print the removed elements.
  • Lines 20-24: Because elements have been removed from the arrays, we print the arrays and discover that they have been modified because of the removeFirst() method.

Free Resources