[swift-evolution] C-style For Loops
Matthijs Hollemans
mail at hollance.com
Sat Dec 5 04:10:42 CST 2015
You’re not the only one, I like them too. :-)
I notice that the SE-0007 proposal only includes positive feedback from the community. I hope that counter arguments will be added too.
The thing that bothers me about this first batch of proposals is that they seem to be about “dumbing down” the language. Personally, I think it would be a mistake to remove “power” features such as the C-style for loop. I like Swift but I don’t want it to hold my hand all the time.
You may think the following is horrible code — I like the expressiveness:
extension LinkedList {
public func reverse() {
for var node = head; node != nil; head = node, node = node!.previous {
// swap next and previous
}
}
}
Another example from the same LinkedList class. It finds the right place to insert a new node:
for next = head; next != nil && index > 0; prev = next, next = next!.next, --index { }
Extreme? Probably, but I like it better than the same thing done in five lines of while loop.
Another benefit of a C-style for loop is that it simply ignores the loop when n <= i, as in the following example,
for var i = 100; i < n; ++i { ...
while the Swifty version gives an error because it cannot create a range where the end is smaller than the start:
for i in 100..<n { ...
Of course, you can add an if-statement to catch this but in the C-style loop this is implicit. Hence, it is more expressive.
Personally, I tend to use for-in as much as possible but I dislike it for going backwards. It’s a style thing but I much prefer,
for var i = 100; i > 0; --i { ...
over:
for i in 100.stride(to: 0, by: -1) { ...
Ideally I’d write this instead, but Swift doesn’t allow such ranges:
for i in 100...1 {
In all these examples, I admit that a C-style for loop is harder to learn. So what? People are only beginners for a short time. I only have a little insight into this but from what I can tell, most beginners don’t have a problem learning the language so much as the frameworks.
We shouldn’t “simplify” the language in the belief that this will help beginners, without a clear understanding of what sort of problems beginners actually have. So far all I’ve seen are assumptions, not actual data. (I only have anecdotal evidence myself.)
Just to be clear: I’m not against making the language easier to learn, but that should not get in the way of allowing more advanced programmers to do their jobs.
-Matthijs
> On 5 dec. 2015, at 08:54, Roland King <rols at rols.org> wrote:
>
> I must be the only person who still likes C-style for loops on occasion. eg a loop with something floating point
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151205/5fd9c7ec/attachment-0001.html>
More information about the swift-evolution
mailing list