Swift Array removeSubrange()

The removeSubrange() method removes elements present in the specified indices from the array.

Example


removeSubrange() Syntax

The syntax of the array removeSubrange() method is:

array.removeSubrange(fromIndex...toIndex)

Here, array is an object of the Array class.


removeSubrange() Parameters

The removeSubrange() method takes a single parameter consisting of the following:

  • fromIndex - the starting position from where elements are removed
  • toIndex - the ending position up to which elements are removed
  • ... - the closed range operator (we can use any type of range operator)

removeSubrange() Return Value

The removeSubrange() method doesn't return any value. Rather, it removes a portion of the array.


Example 1: Swift Array removeSubrange()

Output

Original Array: [1, 2, 3, 4, 5, 6]
Updated Array: [1, 5, 6]

Here, we have used the removeSubrange() method to remove all the elements from index 1 to index 3.


Example 2: Using half-open Range With removeSubrange()

Output

[1, 4, 5, 6]

In the above example, we have used the removeSubrange() method and half-open range to remove a portion of the array. Notice the line,

languages.removeSubrange(1..<3)

Here, ..< is the half-open range. So the upper bound (last index) is excluded. So, only the element of index 1 and index 2 is removed.

To learn more about ranges, visit Swift Range.