kevlar924
kevlar924

Reputation: 65

Is it safe to remove values from a dictionary while iterating in swift?

So my code hasn't crashed, but this feels like it shouldn't be safe, but I can't find a clear answer in the swift docs. I'm iterating over a dictionary with a for-in loop and removing those elements if not found in a reference array. I'm wondering if this is safe, and if so, why?

    func cleanupETADictionary(trips: [Int64]){
        for (tripId, _) in etaDictionary{
            if !trips.contains(tripId){
                etaDictionary.removeValue(forKey: tripId)
            }
        }
    }

Upvotes: 3

Views: 1353

Answers (1)

user652038
user652038

Reputation:

The iteration does not work like you're thinking it does. Your iterated etaDictionary is a copy of the original. Dictionaries are value types in Swift.

Clear example:

var dictionary = [1: 1, 2: 2, 3: 3, 4: 4, 5: 5]

for kvp in dictionary {
  dictionary = [:]
  print(kvp)
  print(dictionary.count)
}

outputs:

(key: 5, value: 5)
0
(key: 3, value: 3)
0
(key: 4, value: 4)
0
(key: 1, value: 1)
0
(key: 2, value: 2)
0

There's a name for your for loop, though; it is called filter. Use it instead.

func cleanupETADictionary(trips: [Int64]){
  etaDictionary = etaDictionary.filter { trips.contains($0.key) }
}

Upvotes: 3

Related Questions