Your expectation that you can mutate a dictionary passed into a function is wrong, for the simple reason that a dictionary in Swift is a value type. And the types inside the dictionary, String and Int, are values too. This means that, in effect, the parameter dict
is a copy of the original dictAges
. Nothing that you do to dict
can have any effect on dictAges
.
This is a sign that you should rethink your entire architecture. If it was wrong to enter a negative number as an age, you should have caught that up front, as it was being entered. In effect, your entire use of a dictionary of Ints as the model here is probably incorrect. You should have used a dictionary of Person, where Person is a struct with an age
and a setter that prevents an age
from being negative in the first place.
If you must have a function that runs through an arbitrary dictionary and fixes the values to be nonnegative, make that a feature of dictionaries themselves:
var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]
extension Dictionary where Value : SignedInteger {
mutating func fixAges() {
for (k,v) in self {
if v < 0 {
self[k] = 0
}
}
}
}
dictAges.fixAges()