Replaces a range of elements with the elements in the specified collection.
SDK
- Xcode 10.2+
Framework
- Swift Standard Library
Declaration
mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where Element == C.Element, C : Collection
Parameters
subrangeThe subrange of the array to replace. The start and end of a subrange must be valid indices of the array.
newElementsThe new elements to add to the array.
Discussion
This method has the effect of removing the specified range of elements from the array and inserting the new elements at the same location. The number of new elements need not match the number of elements being removed.
In this example, three elements in the middle of an array of integers are replaced by the five elements of a Repeated<Int> instance.
var nums = [10, 20, 30, 40, 50]
nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
print(nums)
// Prints "[10, 1, 1, 1, 1, 1, 50]"
If you pass a zero-length range as the subrange parameter, this method inserts the elements of new at subrange. Calling the insert(contents method instead is preferred.
Likewise, if you pass a zero-length collection as the new parameter, this method removes the elements in the given subrange without replacement. Calling the remove method instead is preferred.
Complexity: O(n + m), where n is length of the array and m is the length of new. If the call to this method simply appends the contents of new to the array, this method is equivalent to append(contents.