News for hackers. Stuff that matters.
Re:Swift System Is Now Open Source by santraginean on Friday September 25, 2020 @10:26PM (#24595953)
In every language I’ve used with a for-in construct (or equivalent), the iterated variable is scoped to the loop. That seems to be implied by the syntax, too; it’s equivalent to “for all i in [1,9] where i mod 2 = 0”. If you saw that in a math context, you’d expect i to have no meaning beyond the iteration.

Is there a case to be made for other behavior? Or an example of a language that intentionally treats it any differently? (Unless you go out of your way to iterate over a variable you’ve declared in an outer scope in C, but then that’s not really a for-in construct.)

Re:Swift System Is Now Open Source by anonymoushn on Friday September 25, 2020 @10:58PM (#24596068)
Python and JavaScript are languages that do not behave the way you mentioned.
Re:Swift System Is Now Open Source by santraginean on Saturday September 26, 2020 @12:29AM (#24596421)
JS works that way with plain for loops, but not for-in or for-of. The following fails on the last line, for example:

  for (const i in [1,2,3,4]) {
    alert(i);
  }
  alert("i is now " + i); // ReferenceError
(Not that JS is exactly known for consistent and predictable behavior on edge cases, of course...)

Python I don’t have experience with, and it appears I stand corrected on that front! I wonder how intentional it is, and what sort of use case it enables (and if it’s considered good practice to use).

Re:Swift System Is Now Open Source by anonymoushn on Saturday September 26, 2020 @12:46AM (#24596499)
Python does this mostly because it doesn't have block scope, only function scope like JS's `var`. After using Python for a decade, I think this is mostly a mistake. I would configure (or edit) my linter to prevent me from using it if I needed to write a lot more Python.