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

John McCall rjmccall at apple.com
Mon Dec 14 14:03:30 CST 2015


> On Dec 14, 2015, at 9:29 AM, Joe Groff via swift-evolution <swift-evolution at swift.org> wrote:
>> On Dec 11, 2015, at 11:50 PM, Chris Lattner via swift-evolution <swift-evolution at swift.org <mailto: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.

Interesting observation from when Doug and I were discussing this:  index + subscript is also cheaper than generators for non-mutating for loops, at least for certain kinds of Sequence.  At the very least, it requires less heroism from the mandatory optimizer to get C-like performance at -O0.  And the code pattern would *very* closely parallel what we would presumably emit for an mutating for loop.

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


More information about the swift-evolution mailing list