Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
swift
communitycreator

What is the removeFirst() method in Swift?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
Get first elements of an array with removeFirst()

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.

RELATED TAGS

array
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring