Idea: mutatingForEach for Collections

As the unofficial torch-bearer of the “Collection.indices is a potential performance trap” caravan, I would be remiss not to point out that the proper way to do this (as I described here in the previous thread) is:

var i = startIndex
while i != endIndex {
  try f(&self[i])        OR        self[i] = try f(self[i])
  formIndex(after: &i)
}

The “OR” there is because it is not obvious whether f should take its own argument inout. Taking it inout makes life easier when you have a collection-of-collections that you want to mutate in place (as I described here in the previous thread), but taking it non-inout lets you pass any (Element)->Element function as the transform.

3 Likes