Swift Array removeSubrange()

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

Example

var languages = ["Swift", "English", "French", "Java", "C"]

// remove "English" and "French" from languages languages.removeSubrange(1...2)
print(languages) // Output: ["Swift", "Java", "C"]

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()

var languages = [1, 2, 3, 4, 5, 6]

print("Original Array:", languages)

// remove elements from index 1 to 3 languages.removeSubrange(1...3)
print("Updated Array:", languages)

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()

var languages = [1, 2, 3, 4, 5, 6]

// remove elements from index 1 to 2 languages.removeSubrange(1..<3)
print(languages)

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.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges