Pitch: Introduce `for borrow` and `for inout` to provide non-copying collection iteration

At a level above just Swift, I personally consider mutating the collection you're iterating over to be a pattern that is confusing enough to just outright refuse to compile. IMO all of:

  • It's undefined behavior
  • It crashes at runtime
  • It doesn't affect the iteration
  • It affects the iteration as though you were just indexing into the collection

are all surprising in their own ways and it should probably just be banned without the user somehow specifying what they want to happen, e.g. by writing for x in copy object.ivar or something.

6 Likes