← All languages
Swift function of the day
Random

Array.removeFirst

Remove and return the first element of the array.

Description

The removeFirst method removes and returns the first element of the array. The array must not be empty; calling removeFirst on an empty array triggers a runtime error.

There is also removeFirst(_:) which removes the specified number of elements from the beginning.

removeFirst has O(n) complexity because all remaining elements must be shifted forward to fill the gap.

Example

var queue = ["first", "second", "third"]
let front = queue.removeFirst()
print(front)  // "first"
print(queue)  // ["second", "third"]

Reference