removeFirst() method removes the first element from the array.
var brands = ["Dell", "Apple", "Razer"]// removes and returns first element from brands print(brands.removeFirst())// Output: Dell
The syntax of the array
removeFirst() method is:
Here, array is an object of the
removeFirst() method can take a single parameter:
- i (optional) - number of elements to be removed from the beginning of the array
removeFirst() Return Value
- returns the removed element from the array
Example 1: Swift Array removeFirst()
var country = ["Nepal", "Greece", "Spain"]// removes and returns first element from country print(country.removeFirst())// print the modified array print(country)
Nepal ["Greece", "Spain"]
Here, we have used the
removeFirst() method to remove the first element from the country array.
After removing the first element, we have printed the modified array.
Example 2: Remove Multiple Number of Elements
var languages = ["Swift", "Python", "Java"] print("Before removeFirst():", languages)// removes first two elements from languages languages.removeFirst(2)print("After removeFirst():", languages)
Before removeFirst(): ["Swift", "Python", "Java"] After removeFirst(): ["Java"]
languages.removeFirst(2) removes the first 2 elements from languages.