Home > Net >  Swift: Array - removing elements when condition is met
Swift: Array - removing elements when condition is met

Time:10-31

lets say I have a list of features lasting only a certain amount of time

I periodically loop over an array of features checking if the time is over. when the condition is met I remove the particular element but I get an index error - because the array length changes and the for loop still goes over the "old" length of the array..

what's the proper way of doing this? (lets say the array is very big, do I need to make a new array, do I need to make a second loop ? ... )

struct Feature {
    let name: String
    var remains: Int
}
var features = [Feature(name: "1", remains: 2), Feature(name: "2", remains: 3), Feature(name: "3", remains: 3)]

while true {
for index in 0..<features.count {
    features[index].remains -= 1
    if features[index].remains == 0 {
        features.remove(at: index)
    }
}
}


CodePudding user response:

If this code snippet is really what you need to do (as @Joakim says, there may be other options), you need to make sure that indices remain valid after deleting objects.

One easy way to achieve this is by going through the array backwards, from end to start, by simply adding a .reversed():

for index in (0..<features.count).reversed() { ... }

That said, if you can move the deletion of all items where remains == 0 to a later pass, then it is as simple as

features.removeAll { $0.remains == 0 }

CodePudding user response:

If the array is very big, I would say it would be much simpler to keep an external variable and increase it instead of decreasing the value in all the data.

var currentLimit: Int = 0

...

curentLimit  = 1
features.removeAll { $0.remains < currentLimit }
  • Related