[swift-evolution] Should we relax restriction on closing over outer scope in class declarations?

Marinus van der Lugt rien at starbase55.com
Fri Dec 23 01:45:56 CST 2016


> On 22 Dec 2016, at 22:39, Micah Hainline via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Currently we allow declarations of a new class in local scope, but
> nothing can be referenced from the outer scope. Thus this is illegal:
> 
> ```
> func foo() {
>   let widgetString: String = createWidgetString()
>   class SimpleProvider: WidgetStringProvider {
>      func provideWidgetString() -> String {
>         return widgetString // Illegal, defined in outer scope
>      }
>   }
>   doThingsWithWidget(provider: WidgetStringProvider())
> }
> ```
> 
> I'm trying to feel out the edges of this decision, and figure out why
> exactly this isn't allowed now, and how we might want to relax this in

IMO that questions is backward. The scoping rules being what they are ensure that designers do this exactly because of the scoping rules.

Thus the answer is: Because the designer of the code wanted that restriction.



> the future if possible. While not a common construct, it is a useful
> one.
> 
> Obviously there are ways around it, very simple to create an init and
> a private let and do something like this:
> 
> ```
> func foo() {
>   let widgetString: String = createWidgetString()
>   class SimpleProvider: WidgetStringProvider {
>      private let widgetString: String
> 
>      init(widgetString: String) {
>         self.widgetString = widgetString
>      }
> 
>      func provideWidgetString() -> String {
>         return widgetString // now legal, references
> SimpleProvider.widgetString
>      }
>   }
>   doThingsWithWidget(provider: WidgetStringProvider(widgetString:
> widgetString))
> }
> ```
> 
> That's boilerplate I don't want to write though, as it somewhat
> detracts from the readability of the structure. I'm not super
> interested in defending the concept of local class definitions itself,
> it's already allowed in the language, I'm just interested in the
> syntax limitation and where that line might be able to be redrawn.
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list