Remove objects at specific indexes from Array in Swift 5
What you can do:
- Get all indices
- Sort them descending
- Iterate over the indices, and remove the item at that index
Why reversed? Because else, imagine you have the indices [0, 1], and your array is [A, B, C]
If you start looping on the indices, you'll have :
0: Remove first from [A, B, C] -> [B, C]
1: Remove second from [B, C] -> [B]
So, if you are using Swift Array:
let indices = listToBeRemoved.map{ $0.row }.sorted()
indices.reversed().forEach{ listArray.remove(at: $0) }
Since you are using NSMutableArray (I'd strongly recommend you to avoir NSStuff when Stuff is available): listArray.remove(at: $0)
is listArray.removeObject(at: $0)
Another possible solution:
let indices = IndexSet(listToBeRemoved.map{ $0.row })
listArray.removeObjects(at: indices) //Objective-C
listArray.remove(attOffsets: indices) //Swift
Swift remove objects in Array range
Use removeSubrange
method of array. Make a valid range
by element location
and length
.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let range = 1...3
array.removeSubrange(range)
print(array)
Output: [1, 5, 6, 7, 8, 9, 10]
Note: Range should be a valid range I mean it should not be out from array.
Here is yours way (by for loop)
We can not remove objects by their indexes in a loop because every time object removes array's count and objects indexes will be change so out of range crash can come or you might get a wrong output. So you will have to take help of another array. See below example:-
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var newArray: [Int] = []
let minRange = 1
let maxRange = 3
for i in 0..<array.count {
if i >= minRange && i <= maxRange {
/// Avoid
continue
}
newArray.append(array[i])
}
print(newArray)
Output: [1, 5, 6, 7, 8, 9, 10]
Swift 3 Array, remove more than one item at once, with .remove(at: i)
It's possible if the indexes are continuous using removeSubrange
method.
For example, if you would like to remove items at index 3 to 5:
myArray.removeSubrange(ClosedRange(uncheckedBounds: (lower: 3, upper: 5)))
For non-continuous indexes, I would recommend remove items with larger index to smaller one. There is no benefit I could think of of removing items "at the same time" in one-liner except the code could be shorter. You can do so with an extension method:
extension Array {
mutating func remove(at indexes: [Int]) {
for index in indexes.sorted(by: >) {
remove(at: index)
}
}
}
Then:
myArray.remove(at: [3, 5, 8, 12])
UPDATE: using the solution above, you would need to ensure the indexes array does not contain duplicated indexes. Or you can avoid the duplicates as below:
extension Array {
mutating func remove(at indexes: [Int]) {
var lastIndex: Int? = nil
for index in indexes.sorted(by: >) {
guard lastIndex != index else {
continue
}
remove(at: index)
lastIndex = index
}
}
}
var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
myArray.remove(at: [5, 3, 5, 12]) // duplicated index 5
// result: [0, 1, 2, 4, 6, 7, 8, 9, 10, 11, 13] only 3 elements are removed
Swift: Excluding a specific index from an array when filtering
You can use enumerated()
to convert a sequence(eg. Arrays) to a sequence of tuples with an integer counter and element paired together
var a = [1,2,3,4,5,6,7]
var c = 1
let value = a.enumerated().reduce(1) { (_, arg1) -> Int in
let (index, element) = arg1
c = index != 2 ? c*element : c
return c
}
print(value) // prints 1680 i.e. excluding index 2
array removeObjectsAtIndexes:
use syntax like this for crash free delete;
NSArray *array = [NSArray arrayWithArray: _targets];
for(CCSprite *sprite in array)
{
if(sprite.tag == kToDelete) //mark somewhere in game :or use ur logic here
{
[_targets removeObject: sprite];
[sprite stopAllActions];
[sprite removeFromParentAndCleanup:YES];
}
}
How convert [Int] to int?
index
is array of Int. But you need to pass Int
to the remove
method.
If you want to remove all objects for selected row indexes, than write:
let indexes = tableView.selectedRowIndexes.map { Int($0) }
indexes.reversed().forEach { arrDomains.remove(at: $0) }
If you want to remove object at some index, than write:
guard let index = tableView.selectedRowIndexes.map { Int($0) }.first(where: { /*.your condition here */ }) else { return }
arrDomains.remove(at: $0)
Related Topics
Accessing an Enumeration Association Value in Swift
All Dates Between Two Date Objects (Swift)
Strange Swift Numbers Type Casting
How to Make a Weak Protocol Reference in 'Pure' Swift (Without @Objc)
Opt Out of Uiscenedelegate/Swiftui on Ios
What's the Difference Between "As", "As!", and "As"
Firestore Search Array Contains For Multiple Values
Cfrunloop in Swift Command Line Program
How to Convert Unix Epoch Time to Date and Time in iOS Swift
What Is the "Some" Keyword in Swift(Ui)
Input from the Keyboard in Command Line Application
How to Hash Nsstring With Sha1 in Swift
How to Unwrap an Optional Value from Any Type
How to Stop a Dispatchworkitem in Gcd
Differences in Nsdatecomponents Syntax
How to Display an Activity Indicator With Text on iOS 8 With Swift