Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
arrayutils
communitycreator

Get all elements of an array dropping first "n" elements in Swift

Programming Bytes

Overview

We can use the dropFirst method to drop the first n elements and return the remaining elements of a particular array.

Syntax

func dropFirst(_ k: Int = 1) -> ArraySlice<Element>
Syntax for the "dropFirst" method

Parameters

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.

Return value

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.

Code

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))")
Implementation of the "dropFirst" method

Code explanation

  • Line 4: We create a new array, numbers, with 5 elements.
  • Line 10: We use the 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.
  • Line 13: We use the 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.
  • Line 16: We use the 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

swift
arrayutils
communitycreator
RELATED COURSES

View all Courses

Keep Exploring