Why can't extensions that declare protocol conformance be set to a specific access level?

The compiler won't allow this:


private extension MyClass : SomeProtocol {

}


The error is:


'private' modifier cannot be used with extensions that declare protocol conformances


I'm already aware of the first level of answer to this question, which is that it can't be done because the documentation for access control and extensions says:


Adding Protocol Conformance with an Extension

You cannot provide an explicit access level modifier for an extension if you are using that extension to add protocol conformance. Instead, the protocol’s own access level is used to provide the default access level for each protocol requirement implementation within the extension.


What I would like to know is what the rationale or technical limitation is for imposing this restriction.


It would be very useful to me to be able to privately adopt a protocol within a class or file, but not add that conformance publicly or internally. This pattern is often considered a best practice in Objective-C where class extensions declare protocol conformance that isn't visible from the public header file, e.g.


@interface MyViewController () <UITableViewDataSource>
@end

@implementation MyViewController
...
// pass self as a data source to a UITableView somewhere in here, which works because I privately declared conformance to the UITableViewDataSource protocol
...
@end


Using this pattern, the entire rest of the app doesn't need to worry about what to do with methods like "tableView:cellForRowAtIndexPath:" and "tableView:numberOfRowsInSection:" on my view controller class, which have nothing to do with its public contract.


Using the rest of Swift's access control behavior as an example, it seems like it would make more sense to allow developers to declare an access level modifier on a conforming extension, and that conformance would then have an access level matching the least of those declared by the protocol itself and the extension.

Submit a bug report. It's the only way of officially registering an opinion — what you say here doesn't really count.


Feel free to reference my bug report making the exact same request: #21577990

Thanks for that feedback and glad you've already filed a radar for this! I will as well.


Based on the documentation referenced in my earlier post, it sounds like this was a deliberate decision rather than an unexpected bug. I was hoping, if that's the case, that someone from the Swift team might be willing to share the rationale behind the decision.


But my hope is that it's just a not-yet-implemented feature that is intended to go in sooner than later.

Why can't extensions that declare protocol conformance be set to a specific access level?
 
 
Q