2

I need to remove a range of elements from an array in Swift. Here is the javascript version of exactly what I need to do in Swift: Remove a range of elements from an array

javascript code: 'array.splice(start, deleteCount)'

I have tried to use the ".removeSubrange" instance but Xcode gives the following warning:

"Variable 'array1Adjusted' inferred to have type '()', which may be unexpected"

Here is my simple code:

var array1 = [10,20,30,40,50,60,70,80,90,100]

var array1Adjusted = array1.removeSubrange(5..<9)

And next I need to find the sum of all the elements of array1Adjusted...

var sumArray1Adjusted = array1Adjusted.reduce(0, +)

...but I get the following error:

"Value of tuple type '()' has no member 'reduce'"

1 Answers1

4

array1.removeSubrange(5..<9) does work. It just doesn't create a new array that you can assign to array1Adjusted. Instead, it modifies array1 in place.

var array1 = [10,20,30,40,50,60,70,80,90,100]
array1.removeSubrange(5..<9)
print(array1) // [10, 20, 30, 40, 50, 100]

If you don't want to modify array1, you can do:

let everythingExcept5to9 = array1[...5] + array1[9...]
print(everythingExcept5to9) // [10, 20, 30, 40, 50, 100]

Note that everythingExcept5to9 is an ArraySlice, which is a "view" into the original array you sliced it from. The slice would have the old array's indices, so if you want a proper new array, you should do:

let newArray = Array(array1[...5] + array1[9...])
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Another option is using compactMap `let array1Adjusted = array1.indices.compactMap { 5..<9 ~= $0 ? nil : array1[$0] }` – Leo Dabus Oct 06 '22 at 21:12