Re:Swift's Evolution
by andybak on Saturday June 03, 2017 @12:20PM
(#14477054)
I agree. Looping over a numeric sequence is simply a specific case of looping over any collection. A language should reflect this. It feels so natural to write:
and very easy to move from that to a functional style:
or
The number of times I also need a integer counter is fairly small.
[ Parent
| on HN ]
When you do need an integer counter, the best way to have it is to create a new collection consisting of (index, element) pairs. Swift (and many other languages) make this easy:
for (index, element) in collection.enumerated()
There are some cases where the C style for loop is the most natural way to express something. For example, looping over NULL-terminated array of pointers is nicely expressed with one (Swift 2-ish pseudocode): for var cursor = ptr; cursor.pointee != nil; cursor += 1
But these situations are really rare, and when you do encounter them, it's not a big deal to transform them into a while loop: var cursor = ptr
while cursor.pointee != nil {
defer { cursor += 1 }
...do stuff...
}And you can trivially package the process into an iterator anyway if it's a case you encounter often.
result := collection collect:[ :a | a process ].
result := collection collect process.
collection do process.
1 to: 10 do: [ :i | stdout println:i ].
stdout do println: (1 to: 10).
All just plain messages and plain message syntax, no special control structures needed.