Context
Swift programmers can currently use closures to embed a snippet of swift code with local variables whose scope does not allow access from the closure's parent scope. Of course, this allows programmers to conveniently reuse variable names in closures, as it limits the scope of local variables to only the portion of code in which they are needed.
Consider a feature which works in a somewhat opposite way; instead of limiting the outer scope from accessing the inner scope, we limit the inner scope by explicitly declaring which names are forbidden in the inner scope.
Potential Benefits
- Limiting scope can protect the programmer from referencing names which are not relevant to subsequent lines of code. This provides a sort of "assertion" that future modifications to the code will not depend on the state of explicitly listed outside variables.
- Incentivizes grouping related single-use-case code into sections of more specific behavior
- Provides an alternative to simply using a function declared outside of the existing scope (e.g. you can get the proposed behavior by writing a function and passing all relevant parameters, but this would mean pulling out code that may be specific to the scope of the function in a way that confuses collaborators who see the newly extracted code as a potentially reusable snippet of behavior).
Potential syntax
func loadViews() {
let newView1 = { <self.view> // potential syntax for indicating that self.view should not be accessible in this embedded closure
// ... code which is not allowed to access self.view
}()
let newView2 = { <self.view> // potential syntax for indicating that self.view should not be accessible in this embedded closure
// ... code which is not allowed to access self.view
}()
self.stackSubview(newView1)
self.stackSubview(newView2)
}
Relevant Inspiration
In my implementation of an algorithm which should not be split into multiple functions, I found myself at risk of accidentally using local variables with similar names that are relevant to most of, but not all of the body of the function. A medium-sized clutter of variable names put me at risk of catastrophically using a variable, and I wished that there had been some sort of assertion to ensure that I or another programmer would never make that mistake.
Consequences of the change
This change does not have to affect compiler performance with low-level checks on access legality; it could simply serve as a safety check at the semantic analysis stage. I haven't fully developed this idea or alternative ways to syntactically support this feature, so any input is appreciated.