- Pitch: Mutating forEach

This discussion has made me think about the possibility of for as a statement-expression. Swift has already crossed the Rubicon with if expressions. Would for expressions satisfy @aggie33’s desire, or would it be “almost completely unlike” what people are asking for?

let s1 = for x in [1, 2, 3] { x }
// s1 == [1, 2, 3] as some Sequence
// a synonym for [1, 2, 3].map { $0 }

let s2 = for x in [1, 2, 3, 4, 5] {
  if x == 2 { continue }
  else if x == 4 { break }
  else { x }
// s2 == [1, 3] as some Sequence
// not all iterations need to produce a value

let s3: [Int] = for x in [1, 2, 3] { x }
// s3 == [1, 2, 3]
// because people probably want to work with a Collection

let s4 = for await x in someAsyncSequence { x }
// equivalent to someAsyncSequence.map { $0 }

Seems pretty clear to me, and it doesn't seem particularly surprising. It would generally be something like

let someSequence = ...
for value in someSequence {

(ignoring single iteration sequences)

And really, the primary purpose of lazy is to avoid creating intermediate collections. It may optimize by not iterating all elements, like a lazy contains can, but it's not a guarantee. In fact, I'm pretty sure most lazy sequences Swift ships with will iterate all elements of the incoming collection.

And no, for expressions can't replace forEach, especially if we had a form that returned the collection so it could be in the middle of a chain.

Someone Else might challenge you to first state what forEach does that can’t be replaced by a for…in loop. :wink:

I guess it won't be possible to have a multi statement expression inside? Why do you want those equivalents? Or do you want to get rid of the equivalents in favour of the new "for"?

See the "according" topic.

Jon asserted that for expressions cannot replace forEach. There’s one concrete example in that other thread of something forEach can do (iterate over the projected values of a property-wrapped collection). That is totally fixable, and probably not what Jon was referring to. I’m not trying to debate Jon, just pointing out that without substantiating evidence it’s not a very strong argument.