For example i have an array
var array = [1, 2, 3, 4]
I want to remove item at index 1 then at index 3 "let it be in a for loop".
But removing the item at index 1 will move the item at index 3 to index 2, thus messing up the second removal.
Any suggestions ?
Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.
To remove an element from the Swift Array, use array. remove(at:index) method. Remember that the index of an array starts at 0. If you want to remove ith element use the index as (i-1).
Swift version: 5.6. The reduce() method iterates over all items in array, combining them together somehow until you end up with a single value.
The capacity property returns the total number of elements present in the array without allocating any additional storage.
Given your array
var numbers = [1, 2, 3, 4]
and a Set
of indexes you want to remove
let indexesToRemove: Set = [1, 3]
You want to remove the values "2" and "4".
Just write
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains($0.offset) }
.map { $0.element }
Result
print(numbers) // [1, 3]
It's simple. delete items from the end.
First delete 3 and after that delete 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With