# Pitch: Allow Protocols to be Nested in Non-Generic Contexts

**URL:** <https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285>\
**Category:** Pitches\
**Created:** [May 31, 2023, 6:16pm UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285 "2023-05-31T18:16:05Z")\
**Posts on this page:** 14\
**Page:** 2

<div class="post-metadata">

**Author:** ![ensan-hcl](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ensan-hcl/32/15186_2.png) [@ensan-hcl](https://forums.swift.org/u/ensan-hcl)\
**Post date:** [June 2, 2023, 2:25am UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/22 "2023-06-02T02:25:49Z")

</div>

Understood. But I also think we can disable satisfying `associatedtype` requirement with nested protocol in Swift 5.9 or later, since this is a new feature which will be introduced after [SE-0335](https://forums.swift.org/t/se-0335-introduce-existential-any) is introduced.  
I believe source break creates a bit difficult situation, consider the following case.

```swift
// Swift 5
public protocol P {
     associatedtype Q
}
public struct A: P {
    // this is now satisfying associatedtype requirement
    protocol Q {}
}

// usage as constraint
extension B: A.Q { /* ... */ }
// usage as type
let value: A.Q = /* ... */

```

In Swift 6, as `Q` is no longer usable as a type, you have to change the type into like this.

```swift
public struct A: P {
    public typealias Q = any _Q
    public protocol _Q {}
}

```

However, making such a change is API-breaking, because the usage of `A.Q` as constraint is no longer possible. While `--enable-upcoming-feature ExistentialAny` will expose such risks, I also think avoiding such scenario from the beginning of nested protocol introduction is worth considering.

---

<div class="post-metadata">

**Author:** ![JuneBash](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/junebash/32/19323_2.png) [@JuneBash](https://forums.swift.org/u/JuneBash)\
**Post date:** [June 2, 2023, 3:10am UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/23 "2023-06-02T03:10:11Z")

</div>

Very excited to see this being worked on! I was planning to learn a lot more about the compiler and take it on last year, but alas, life got in the way, so I'm happy to see it be picked up!

---

<div class="post-metadata">

**Author:** ![anon9791410](https://avatars.discourse-cdn.com/v4/letter/a/9fc348/32.png) [@anon9791410](https://forums.swift.org/u/anon9791410)\
**Post date:** [June 8, 2023, 5:37pm UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/24 "2023-06-08T17:37:59Z")

</div>

> [@Karl](#):
>
> ```swift
> func doSomething() {  
> func impl<T: Abstraction>(_ input: T) -> T.ResultType {
> // ...
> }
> }
> 
> ```

This pitch is good, but should _at least_ come with a caveat about this spelling. Outside of a function, it would be a protocol extension.

```swift
fileprivate extension Abstraction {
  var impl: ResultType { // …
}

```

Without nested protocol _extensions_, switching to the function form will be necessary, trading good spelling for good scoping. 😔 So I don't think this pitch should be implemented without being paired with nested extensions.

> [@\[Pre-pitch\] Allow extension of nested members within extension of parent](https://forums.swift.org/t/pre-pitch-allow-extension-of-nested-members-within-extension-of-parent/65423):
>
> This is a tiny syntactic sugar pitch. Swift's ability to group code by use of extension is probably one of the best features of Swift and something [Apple themselves use a lot](https://github.com/apple/swift-collections/tree/main/Sources/OrderedCollections/OrderedDictionary), combined with Swift's ability to nest types these two language features make up the backbone of what we love about Swift. Today extensions are limited to global scope, I cannot extend a nested type within an extension of the enclosing parent type. This makes code hard to read, I would argue. Simple case study (sorry for…

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [June 9, 2023, 9:29am UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/25 "2023-06-09T09:29:03Z")

</div>

I think it would be nice to allow nesting extensions within functions - it's one of the missing pieces before we're able to nest entire Swift programs within functions, which would be extremely cool (there are some things you can _only_ do with an extension -- like adding a protocol conformance to a stdlib type).

> [@anon9791410](#):
>
> So I don't think this pitch should be implemented without being paired with nested extensions.

I think there is enough here even without support for nesting extensions. There's nothing here which prevents that being added to the language at a later date.

---

<div class="post-metadata">

**Author:** ![bbrk24](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bbrk24/32/27370_2.png) [@bbrk24](https://forums.swift.org/u/bbrk24)\
**Post date:** [June 9, 2023, 11:31am UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/26 "2023-06-09T11:31:06Z")

</div>

> [@Karl](#):
>
> like adding a protocol conformance to a stdlib type

This should definitely not be possible at the function-level. That would mean that the vtable grabbed by `as? SomeProtocol` would differ depending on the current call stack, and it wouldn’t surprise me if that can’t be done.

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [June 9, 2023, 11:39am UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/27 "2023-06-09T11:39:57Z")

</div>

Yeah I suppose - I was thinking more of conformances to function-local protocols:

```swift
func foo() {

  protocol Nested { ... }

  // How do I make 'Int' conform to 'Nested'?
  // I can't write an extension, so I need to wrap it in a local type,
  // which is not nice.
}

```

But yeah, conformances to other protocols could be problematic.

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [July 23, 2023, 5:19pm UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/28 "2023-07-23T17:19:09Z")

</div>

Apologies for not responding to this before. I agree that a nested protocol should not satisfy an associated type requirement.

Especially with the loss of bare protocol existential syntax, the language is moving towards putting a clearer distinction between protocols (i.e. _constraints_) and concrete types. `associatedtype` is currently used to refer to concrete types, and it would be problematic in a lot of senses for it to bind to a nested protocol.

There have been requests in the past for "associated protocols" or something broadly to that effect:

- [Protocols with associated protocols?](https://forums.swift.org/t/protocols-with-associated-protocols/17022)
- [Support for protocols as parameters for constrained generics](https://forums.swift.org/t/support-for-protocols-as-parameters-for-constrained-generics/10009)
- [Generalized supertype constraints](https://forums.swift.org/t/generalized-supertype-constraints/22380)

If we ever did add some kind of associated protocol feature, it might be reasonable to use nested protocols to define them, as we currently can with associated types and nested concrete types.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [July 24, 2023, 4:47am UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/29 "2023-07-24T04:47:14Z")

</div>

> [@Karl](#):
>
> Apologies for not responding to this before. I agree that a nested protocol should not satisfy an associated type requirement.
> 
> Especially with the loss of bare protocol existential syntax, the language is moving towards putting a clearer distinction between protocols (i.e. _constraints_) and concrete types. `associatedtype` is currently used to refer to concrete types, and it would be problematic in a lot of senses for it to bind to a nested protocol.
> 
> There have been requests in the past for "associated protocols" or something broadly to that effect:
> 
> - [Protocols with associated protocols?](https://forums.swift.org/t/protocols-with-associated-protocols/17022)
> - [Support for protocols as parameters for constrained generics](https://forums.swift.org/t/support-for-protocols-as-parameters-for-constrained-generics/10009)
> - [Generalized supertype constraints](https://forums.swift.org/t/generalized-supertype-constraints/22380)
> 
> If we ever did add some kind of associated protocol feature, it might be reasonable to use nested protocols to define them, as we currently can with associated types and nested concrete types.

I agree with this reasoning. However, it occurs to me that this could lead to a wee bit of a problem—well, let's not call it a problem but maybe a complexity or nuance for which we need to specify the behavior in this proposal.

Suppose we have the following type, which would be allowed under your proposal:

```swift
struct S {
  protocol P { }
}

```

I retroactively adopt conformance to the following protocol like so:

```swift
protocol Q {
  associatedtype P = Void
}
extension S: Q { }

```

If the protocol `S.P` does not satisfy the requirement `Q.P` (as you and I agree), then what is the behavior here?

_[Dramatic pause to allow readers to consider their answer before continuing.]_

* * *

As we do not have a partitioned namespace for protocols versus types, I can see two possibilities, one not exactly satisfying for its complexity and one seemingly straightforward but actually unacceptable:

_Option A:_  
By analogy with the case where a protocol requires a property with a different type but same name as a property already on the concrete type, `S.P` _shadows but not override_ the required associated type, which defaults to `Void`. Users really don't like this sort of behavior, but it's quite precedented when it comes to protocol adoption.

> **In the absence of a default specified by \`Q\`...**
>
> users would have to rely on associated type inference or a future formalization of the `@_implements` feature in order to fulfill the requirement. Otherwise, again by analogy with the case where a protocol requires a property with a different type but same name as a property already on the concrete type, users just wouldn't be able to conform.

_Option B:_  
The compiler can just straight-up refuse to compile the retroactive conformance extension. Super straightforward.

Why even contemplate the complexities of Option A? Unless I'm mistaken, Option B breaks the following [promise about what's supported under library evolution](https://github.com/apple/swift/blob/main/docs/LibraryEvolution.rst#protocols):

> A new `associatedtype` requirement may be added (with the appropriate availability), as long as it has a default implementation. If the protocol did not have one or more `associatedtype` requirements before the change, then this is a binary-compatible source-breaking change.

By implication (and afaik it's in fact currently true), where a protocol already has `associatedtype` requirements, adding another one is a binary-compatible and source-compatible change. With lifting of the "`Self` or associated type" restriction on the use of existentials, I believe we're heading towards a state where the later addition of a first `associatedtype` requirement is source-compatible as well.

However, if the compiler would refuse to compile if a nested protocol takes the same name as an associated type requirement, then _no_ protocol could adopt _any_ new `associatedtype` requirements in a source-compatible way even if it supplies a default.

---

<div class="post-metadata">

**Author:** ![ksluder](https://avatars.discourse-cdn.com/v4/letter/k/eada6e/32.png) [@ksluder](https://forums.swift.org/u/ksluder)\
**Post date:** [July 24, 2023, 5:50am UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/30 "2023-07-24T05:50:17Z")

</div>

> [@xwu](#):
>
> By analogy with the case where a protocol requires a property with a different type but same name as a property already on the concrete type, `S.P` _shadows but not override_ the required associated type, which defaults to `Void`. Users really don't like this sort of behavior, but it's quite precedented when it comes to protocol adoption.

And the user would be able to work around this by adding `typealias P = Self.P` to their extension?

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [July 24, 2023, 6:28am UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/31 "2023-07-24T06:28:49Z")

</div>

> [@ksluder](#):
>
> And the user would be able to work around this by adding `typealias P = Self.P` to their extension?

No: I wouldn't think we'd do anything to change the fact that `typealias P` and `protocol P` in the same lexical scope would be (as it currently is) a redeclaration error.

But that is actually immaterial—even if it were not a redeclaration error, the `typealias` declaration would have no effect under Swift 6 rules. The "this" you're asking about a "work around" for is SE-0355: i.e., you're asking if there's some incantation to opt into `P` (the protocol) and `any P` (the existential type) not being distinguished from each other.

I think if we wanted to do that we'd just revoke SE-0355 and allow nested protocols to satisfy associated type requirements as existentials—we wouldn't adopt the diametrically opposite rule into the language and then add additional special-case features to "work around" it on a case-by-case basis.

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [July 24, 2023, 8:16am UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/32 "2023-07-24T08:16:06Z")

</div>

> [@xwu](#):
>
> By analogy with the case where a protocol requires a property with a different type but same name as a property already on the concrete type, `S.P` _shadows but not override_ the required associated type, which defaults to `Void`. Users really don't like this sort of behavior, but it's quite precedented when it comes to protocol adoption.

It is interesting that we do this for properties but not associated types AFAICT:

Property:

```swift
struct S {
    var foo: String { "" }
}

protocol Q {
    var foo: Int { get }
}
extension Q {
    var foo: Int { 42 }
}

// OK
extension S: Q {}

```

Associated Type (with a constraint that means the existing `P` cannot be a witness):

```swift
struct S {
    typealias P = String
}

protocol Q {
    associatedtype P: Numeric = Int
}

// ❌ error: type 'S' does not conform to protocol 'Q'
extension S: Q {}

```

I think it should act like the latter. A nested protocol is not a valid witness to an associated type because it is not a concrete type, just as `String` cannot witness the `Q.P` associated type because it does not meet the `Numeric` constraint.

In fact, despite `Q.P` having a default, I couldn't find _any way_ to implement this conformance. Neither by using inference nor by using `@_implements`. Granted, I was testing within a single file, but I would be surprised if this behaved differently were I to split the types across different modules.

```swift
protocol Q {
    associatedtype P: Numeric = Int
    func foo(_: P)
}

// ❌ error: type 'S' does not conform to protocol 'Q'
extension S: Q {

  @_implements(Q, P)
  typealias Foo = Int

  // None of these make a difference, either.
  // @_implements(Q, foo)
  // @_implements(Q, foo(_:))
  func foo(_: Int) {}
}

```

[Godbolt](https://swift.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:'1',fontScale:14,fontUsePx:'0',j:1,lang:swift,selection:(endColumn:1,endLineNumber:9,positionColumn:1,positionLineNumber:9,selectionStartColumn:1,selectionStartLineNumber:9,startColumn:1,startLineNumber:9),source:'struct+S+%7B%0A++++typealias+P+%3D+String%0A%7D%0A%0Aprotocol+Q+%7B%0A++++associatedtype+P:+Numeric+%3D+Int%0A++++func+foo(_:+P)%0A%7D%0A%0Aextension+S:+Q+%7B%0A%0A++@_implements(Q,+P)%0A++typealias+Foo+%3D+Int%0A%0A++//+@_implements(Q,+foo)%0A++//+@_implements(Q,+foo(_:))%0A++func+foo(_:+Int)+%7B%7D%0A%7D'),l:'5',n:'0',o:'Swift+source+%231',t:'0')),k:50,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:swift58,deviceViewOpen:'1',filters:(b:'0',binary:'1',binaryObject:'1',commentOnly:'0',debugCalls:'1',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'0',trim:'1'),flagsViewOpen:'1',fontScale:14,fontUsePx:'0',j:1,lang:swift,libs:!(),options:'-O',overrides:!(),selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'+x86-64+swiftc+5.8+(Editor+%231)',t:'0')),k:50,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4) if you'd like to try for yourself.

So it seems to me that we are already not meeting the goal that adding an associated type with default is a source-compatible change. It's definitely an issue worth solving, but if it's not an issue introduced by this feature I would say we can consider its solution to be out of scope for this proposal.

The solution would probably be to productise `@_implements`. It doesn't surprise me that it is unable to disambiguate associated types as currently implemented; it is an unofficial feature and appears to be limited in its capabilities.

---

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [July 24, 2023, 3:40pm UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/33 "2023-07-24T15:40:08Z")

</div>

> [@xwu](#):
>
> _no_ protocol could adopt _any_ new `associatedtype` requirements in a source-compatible way even if it supplies a default.

swift's extension-based API model and total lack of namespacing facilities means there are actually very few kinds of additions that can be made to a type's API in a way that is strictly "source-compatible".

even seemingly innocuous changes, like adding an initializer to a protocol as an extension member can cause client code to fail to typecheck or dramatically increase compilation times due to name collisions.

in my view, the fact that adding an associated type requirement risks a name collision with another protocol nested in a retroactively-conformed type is not particularly novel or even remarkable. we have been dealing with variations this problem for a very long time.

---

<div class="post-metadata">

**Author:** ![hborla](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/hborla/32/27563_2.png) [@hborla](https://forums.swift.org/u/hborla)\
**Post date:** [July 24, 2023, 4:06pm UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/34 "2023-07-24T16:06:01Z")

</div>

Hey folks, I've kicked this off for review [here](https://forums.swift.org/t/se-0404-allow-protocols-to-be-nested-in-non-generic-contexts/66332) starting now through August 7th. Please move any further discussion about the witness matching behavior over to the review thread.

Thank you!

Holly Borla  
Review Manager

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [July 24, 2023, 5:00pm UTC](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285/35 "2023-07-24T17:00:17Z")

</div>

Closed on July 24, 2023, 5:00pm UTC



[Previous page](https://forums.swift.org/t/pitch-allow-protocols-to-be-nested-in-non-generic-contexts/65285.md?page=1)
