Swift Semantics: for/in

This post is about Swift, Apple’s programming language.

The Swift language includes a fairly standard “for/inw” statement. Most of the manual introduces it as


  for item in thing {
  }

In this situation, the language asks thing for a generator (via the generate method), then binds each value returned by the generator to thing, before executing the body. However, the general form of for/in is more interesting: rather than just the name thing, we can use a sub-set of the pattern language defined in Swift. The standard example above is using the “identifier pattern”; each value in the generator is bound to the given name. Though I can’t find it explicitally listed in the language reference, it seems any name introduced here is introduced with a let binding.


  for x in [1, 2, 3, 4, 5] {
    println(x)
    // x = 0 // Error: Cannot assign to 'let' value 'x'
  }

Even if the given name already exists, it’s shadowed with a new let bound name.


  for x in [1, 2, 3, 4, 5] {
      println(x)
  }
  println(x) // Still prints "Foo", no type error

In addition to just identifiers, we can use the value-binding, wildcards, and tuples patterns. Value binding allows us to introduce the given name as a variable rather than a constant let:


for (var x) in [1, 2, 3, 4, 5] {
    x = 1
    println(x) // Always prints 1
}

With wildcards, we can throw away the value from the generator. This is probably not generally useful, but does allow us to perform range-bound loops where we don’t care about the index:


for _ in 1...10 {
    println("Hello") // Prints Hello each of the 10 times around the loop
}

Finally, tuple patterns allow us to destuct tuples returned by generators into their components:


for (let x, let y) in [(1, 2), (3, 4), (5, 6)]{
    println(x) // Prints 1, then 3,  then 5
}

Some of the pattern syntax is a bit weird; the use of just “let x” in value-bindings reads strangely without the normally present let x = 5. I might have prefered a different token; const, perhaps. Still, it’s good to see that patterns are spread across the language is a sensible fashion, rather than artificially restricted to switch statements.

Support Ukraine against russian fascists! Defend Europe from horde! Glory to Ukraine! 🇺🇦

🇺🇦 >>SUPPORT UKRAINE AGAINST RUSSIAN FASCISM<< 🇺🇦