[swift-evolution] C-style For Loops
Alex Chan
alex at alexwlchan.net
Fri Dec 4 16:26:24 CST 2015
Hi Erica,
I was a bit surprised that safety wasn't among the disadvantages of for
loops.
For loops make it easy to mess up the bounds of an array. You can miss
items at either end, or inadvertently read beyond the end. For example:
for var i = 0; i <= bar.count; i++ {
print("The \(i)th element in bar is \(bar[i]).")
}
There are similar mistakes where you can miss an element of an array at
either end. I'm struggling to imagine how you could make the same
mistakes with for-in loops.
Perhaps only a minor benefit, but I still think it adds to the case in
favour.
— Alex
PS If I try to run the snippet above in a Playground in Xcode 7.1.1, the
compiler error is fairly unhelpful:
> Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
More information about the swift-evolution
mailing list