Nested types on protocols, protocols on concrete types

A consistent point of frustration for me, and a point of confusion for users new to Swift, is that nested type declarations are not allowed inside of protocol definitions (or their extensions).

Conversely, it is even more confusing that protocol definitions cannot be nested in concrete types! Imagine if instead of UICollectionViewDataSourcePrefetching, we could have UICollectionView.DataSource.Prefetching

We would not have to pollute the global namespace with types that are only relevant in the context of another.

I understand that the namespace debate has raged since before Swift Evolution was a thing. Proponents such as myself have resigned to defining our types on zero case enums. But this doesn’t work for protocols!

What do you think about allowing nested types within protocols, and protocols nested within other types?

7 Likes

The ability in particular to scope enums within a protocol when they are tightly related to a function argument in that protocol is something I've often wished for.

2 Likes

There are several fleshed out pitches on this topic that are worth reviewing. You can find them by searching “nested protocols” on this Forum.

A key difficulty which doesn’t arise with FooBarBaz but with Foo.Bar.Baz is what happens in the latter case with generic parameters, associated types, etc. I would refer you to preceding discussions on the matter instead of trying to repeat everything here.

3 Likes