[swift-evolution] Proposal: "inout" in for loops

Joe Groff jgroff at apple.com
Mon Dec 14 11:29:28 CST 2015


> On Dec 11, 2015, at 11:50 PM, Chris Lattner via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hi Amir,
> 
> Please read up on the semantics of for-in loops & generators, and if you think this is a good idea, then propose the actual language changes necessary to provide this behavior.  Thanks,
> 
> -Chris

An 'inout' for loop would be handy for some use cases, but would probably depend on a MutableCollectionType at minimum rather than any arbitrary SequenceType. You can implement a mutable version of 'forEach' as a higher-order function extension on MutableCollectionType today:

extension MutableCollectionType {
  mutating func mutableForEach(body: (inout Generator.Element) throws -> ()) rethrows {
    for index in indices {
      try body(&self[index])
    }
  }
}

var x = [1,2,3]

x.mutableForEach { (inout y: Int) in y += 1 }

print(x)

If you want to propose this as a language feature, you could use a library implementation like this as a starting point for proposing how it would work.

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151214/60074023/attachment.html>


More information about the swift-evolution mailing list