[swift-evolution] C-style For Loops

Kelly Gerber kellygerber22 at yahoo.com
Sun Dec 6 13:03:33 CST 2015


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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151206/a3fd4836/attachment.html>


More information about the swift-evolution mailing list