remove an element from the beginning of an array in swift

To remove the first element of an array arr in Swift, you can use the removeFirst() method. This method removes the first element of the array and returns it.

main.swift
var arr = [1, 2, 3, 4, 5]
let firstElement = arr.removeFirst() // removes and returns 1
print(arr) // [2, 3, 4, 5]
115 chars
4 lines

Note that removeFirst() is a mutating method, which means it modifies the array in place. If you don't need the removed element, you can simply call removeFirst() without assigning its return value to a variable:

main.swift
var arr = ["apple", "orange", "banana"]
arr.removeFirst() // removes "apple"
print(arr) // ["orange", "banana"]
112 chars
4 lines

If the array is empty when you try to remove the first element, calling removeFirst() will result in a runtime error. To avoid this, you can use the first property to check if the array is not empty before removing the first element:

main.swift
var arr = [Int]()
if let firstElement = arr.first {
    arr.removeFirst() // the array is not empty, remove the first element
} else {
    // the array is empty, do something else
}
182 chars
7 lines

gistlibby LogSnag