What is the replaceSubrange(_:with:) method in Swift?

Overview

The replaceSubrange(_:with:) method is used to replace a sub-range of elements with the contents of another collection or array. This means that it replaces elements within a sub-range of index positions.

Syntax

arr.replaceSubrange(range, with: elements)

Parameters

  • range: This is the range of the elements that we want to replace.

  • elements: These are the elements that we want to use as replacements.

Return value

This method returns a new array with elements in the range replaced with the specified elements.

Code example

// create arrays
var arr1 = [1, 2, 10, 20, 30, 40, 5, 6]
var arr2 = ["a", "b", "c", "x", "y"]
// replace elements within
// some sub-range index positions
arr1.replaceSubrange(2...5, with: [3, 4])
arr2.replaceSubrange(3...4, with: ["d", "e","f"])
// print modified arrays
print(arr1)
print(arr2)

Code explanation

  • Lines 2–3: We create two arrays.
  • Line 7: We use the replaceSubrange(_:with:) method to replace the elements within the index position of the range 2...5. Then, we replace them with the elements 3 and 4.
  • Line 8: We use the replaceSubrange(_:with:) method again to replace elements within the index position of the range 3...4. Then, we replace them with the elements "d", "e", and "f".
  • Lines 11–12: We print the results to the console.

Free Resources