[swift-evolution] [Proposal] Lexical scope statement (with .. do)

Taras Zakharko taras.zakharko at uzh.ch
Sun Dec 27 14:10:30 CST 2015


Quite often, one needs to perform a number of operations on a single object (e.g. call up a bunch of configuration or action methods). This proposal is to extend the ‘do' statement  with an explicit lexical scope feature. For instance, this piece of code

 object.do_something()
 object.do_somethind_else()
 object.prop1 = value

becomes

 do with object // or with object do
 {
   do_something()
   do_somethind_else()
   prop1 = value
 }

Essentially, this construct would introduce a level of lexical scope — explicitly controlled by the programmer, in addition to the implicit scope dictated by statement blocks, closures and self. 

The advantage of this construct is that it allows one to remove boilerplate code for initialisation/configuration as well as adds clear logical separation to the code. Disadvantage is potential shadowing of identifiers in the scope, but this should to be a big issue because the syntax is explicit rather then implicit, meaning that its the programmers job to make sure that no shadowing occurs (btw, compiler could warn about shadowing). The additions to the language syntax is minimal and the implementation should be straightforward (its essentially the same logic as for self). 

Note that this proposal is close to the discussion about popular the implicit self on this mailing list. A body of any method could be understood as wrapped into an implicit 

   do with self {}

Finally, this construct exists in a very similar form in Pascal (no idea if Wirth was inspired by some other feature or not here) and is also present in a bunch of languages that have dynamic scope. Personally, I use it all the time in R and I am loving it. 

If the community thinks this could be a nice addition to the language, I am ready to draft a proposal. Also, apologies if this has been suggested before — it is impossible to keep up with this list. 

Best, 

 Taras


More information about the swift-evolution mailing list