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.
arr.replaceSubrange(range, with: elements)
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.
This method returns a new array with elements in the range
replaced with the specified elements
.
// create arraysvar arr1 = [1, 2, 10, 20, 30, 40, 5, 6]var arr2 = ["a", "b", "c", "x", "y"]// replace elements within// some sub-range index positionsarr1.replaceSubrange(2...5, with: [3, 4])arr2.replaceSubrange(3...4, with: ["d", "e","f"])// print modified arraysprint(arr1)print(arr2)
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
.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"
.