[swift-evolution] [Pitch] Allow nested protocol declarations

Howard Lovatt howard.lovatt at gmail.com
Thu Apr 28 18:42:35 CDT 2016


To get over issues like the inner protocol accessing outer quantities like
properties and generics you could add keyword noaccess (bike-shedding
name) to the declaration to make it clear that it does not have access,
e.g.:

class MyController<T> {
  noaccess protocol Delegate {
    // No access to T
  }
}

Java does something along these lines using static and it works out well.
As an aside static is insufficient in Swift because statics have access to
generics in Swift, unlike Java.

On Friday, 29 April 2016, Douglas Gregor via swift-evolution <
swift-evolution at swift.org> wrote:

>
> On Apr 28, 2016, at 10:15 AM, Brad Hilton via swift-evolution <
> swift-evolution at swift.org
> <javascript:_e(%7B%7D,'cvml','swift-evolution at swift.org');>> wrote:
>
> Type nesting allows some convenient and straightforward semantics that we
> see inside the Swift standard library such as views on String like
> String.CharacterView, String.UnicodeScalarView, etc. However a protocol
> cannot be nested in a type and gives a non-obvious error that the
> “Declaration is only valid at file scope.” Just as other nested types allow
> proper contextual scoping, a nested protocol could make a lot sense for a
> number of patterns. For example, there are many “Delegate” protocols
> throughout the Cocoa frameworks. Here’s a controller/delegate pattern
> before and after type nesting:
>
> // Without type nesting
>
> protocol MyControllerDelegate : class {
>
> }
>
> class MyController {
>
>     weak var delegate: MyControllerDelegate?
>
> }
>
> // With type nesting
>
> class MyController {
>
>     weak var delegate: Delegate?
>
>     protocol Delegate : class {
>
>     }
>
> }
>
> Though the change is mostly semantics, it does allow an explicit
> association between My Controller and the Delegate instead of only a named
> association. It also cleans up the module name space like other nested
> types and makes associated protocols more discoverable in my opinion.
>
> I’d love to hear everyone’s thoughts.
>
>
> Note that this cannot work when any enclosing type is generic, e.g.,
>
> class MyController<T> {
>   protocol Delegate {
>     // I’ve just created a parameterized protocol!
>   }
> }
>
>
> Otherwise, I don’t see any issues with the proposal, and I like that it
> eliminates a large number of top-level names.
>
> - Doug
>
>
>

-- 
-- Howard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160429/0a89672a/attachment.html>


More information about the swift-evolution mailing list