We can use the dropFirst
method to drop the first n
elements and return the remaining elements of a particular array.
func dropFirst(_ k: Int = 1) -> ArraySlice<Element>
The number of elements that need to be dropped from the beginning of the array is passed as an array. This is an optional argument. The default value of the argument is 1
.
This method returns an array. If 0
is passed as an argument, then no element is supposed to be removed from the array. If we pass a value that is larger than the length of the array, then an empty array is returned.
The code written below demonstrates how we can get all the elements of an array after dropping the first n
elements in it:
import Swift // create a array with 5 elements let numbers = [1, 2, 3, 4, 5] // drop first element of the array print(" The array is - \(numbers)") // drop first element of the array print("\n numbers.dropFirst() - \(numbers.dropFirst())") // drop first 2 elmenets of the array print("\n numbers.dropFirst(2) - \(numbers.dropFirst(2))") // drop first 10 elmenets of the array print("\n numbers.dropFirst(10) - \(numbers.dropFirst(10))")
numbers
, with 5 elements.dropFirst
method without any argument(s). The dropFirst
method drops the first element of the array and returns the other elements as a new array. We get [2,3,4,5] as a return value.dropFirst
method with 2
as an argument. The dropFirst
method drops the first two elements of the array and returns the other elements as a new array. We get [3,4,5] as a return value.dropFirst
method with 10
as an argument. The argument value is greater than the length of the array, so the dropFirst
method returns an empty array.RELATED TAGS
CONTRIBUTOR
View all Courses