Why can't Protocols be nested in other Types?

We can nest classes, structs & enums:

class TestClass {
     class OtherClass {}
     struct OtherStruct {}
     enum OtherEnum {}
}


Why can't we also nest protocols?

class TestClass {
     protocol Delegate {}  // error: Declaration is only valid at file scope
}


So far the workaround is to declare it at file scope using and use a typealias instead.

The underscore prefix makes it clear that the global symbol name is not intended for direct use.

class TestClass {
     typealias Delegate = _TestDelegate
}

protocol _TestDelegate {}


Is this just not yet implemented or is there a reason for not supporting that at all?

The protocols from my example could be used in an abstract factory-based design. Abstract factory is one of the most basic design patterns. If you use it or not, this is considered good software design.

Factory is a very widely used pattern *in Java*. It is far from a general good practice in oop design. Yes, it is a basic pattern but it is totally overused and makes simple code often much more complex. Do I really have to point to Factory Factories in Java?

Btw, the problem also exists in the opposite direction:

protocol Parser {
    func parse() throws -> Node

    enum Error {}
    protocol Node {}
}


You cannot declare types inside a protocol, which is a pity if you want good abstraction and good namespacing at the same time.


This will work though:

class Parser {
    func parseNode() throws -> ParserNode {}

    enum Error {}
}


protocol ParserNode {}

Well Swift protocols aren't designed to provide abstraction and namespacing. Of course they will have problem if you try to use them in this manner.


The namespacing mechanism in Swift are modules and for abstraction generic classes with inheritance.

Sorry but this is nonsense.


You're basically saying that nested types are a bug in Swift rather than a feature.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/NestedTypes.html


So far some types support nesting while others don't. So we can consider cases which are not possible at the moment to be a temporary limitation.

As in your linked text: to separate helper classes. This functionality has gone superfluous with the introduction of private. Now you simply put the helper classes in the same file and make them private.

Delegates like most other protocols are not helper classes…

Their whole intention is not be non-private so others can implement them.

So please think what you just wrote and explain why you are wondering that protocols can't be nested in Swift...

You are not helpful at all.

Why can't Protocols be nested in other Types?
 
 
Q