[swift-evolution] C-style For Loops

Erica Sadun erica at ericasadun.com
Sun Dec 6 13:14:32 CST 2015


That is very odd indeed.

If you add explicit capture, the issue goes away:

var handlers: [() -> Void] = []

for i in 0..<5 {
    handlers.append {[i] in print(i, terminator:",") }
}

for handler in handlers {
    handler()  // "0 1 2 3 4"
}

handlers = []

for var i = 0; i < 5; i += 1 {
    handlers.append {[i] in print(i, terminator:",") }
}

print("")
for handler in handlers {
    handler()  // was "5 5 5 5 5", now 1, 2, 3, 4, 5
}

It really seems like a bug to me rather than a feature of the for-loop

-- Erica


> On Dec 6, 2015, at 12:03 PM, Kelly Gerber via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I think that the C-style for loop should be removed from Swift. The scope rules for this for loop are wrong. Every loop sees the same scope. This is a source of bugs if you export the loop variable name outside the scope of the for statement, for example in a closure. The following code illustrates the problem:
> 
> var handlers: [() -> ()] = []
> 
> for i in 0..<5 {
>     handlers.append { print(i) }
> }
> 
> for handler in handlers {
>     handler()  // "0 1 2 3 4"
> }
> 
> handlers = []
> 
> for var i = 0; i < 5; i += 1 {
>     handlers.append { print(i) }
> }
> 
> for handler in handlers {
>     handler()  // "5 5 5 5 5"
> }
> 
> The Swift for-in loop does the right thing naturally. The C-style for loop does the wrong thing naturally. Removing the C-style for loop from Swift will eliminate one more class of possible errors from the language.
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151206/c0d7c9bf/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: open.gif
Type: image/gif
Size: 43 bytes
Desc: not available
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151206/c0d7c9bf/attachment.gif>


More information about the swift-evolution mailing list