Discouraging protocol methods on concrete values

If someone has a reference to the concrete object via a variable that is typed as the protocol then there is no way for the compiler to know that it should disallow calling those functions. The best you could do is to disallow calls to those methods via variables that use the concrete type directly.

C# actually has a way to do this. In C# there’s a concept called explicit interface implementation. When implementing a part of an interface you can qualify the name of the method with the interface name to specify that it is explicit like this:

public class Foo : IFoo
{
    IFoo.FooMethod()
    {
    }
}

The effect of this is that FooMethod can only be called on this object by code that is using the IFoo interface. If you have a variable typed as Foo then you can’t call it.

This basically works by making FooMethod implicitly private. Typically in C# methods fulfilling interface requirements must be declared as public, but for explicit interface implementations the compiler forbids you from specifying the access level, and instead it is implicitly private but callable via the interface.

One use case for this in C# is for when you have to make something conform to an interface for implementation reasons (maybe it’s a delegate for some other object and has to conform to the delegate interface), but you don’t want that interface to be part of your contract to other clients. You can essentially conform privately.

Another use case is if you want to provide a better method (maybe with a more useful return type) that is equivalent and encourage its use instead. In that case you can still conform to the interface, but make this method private while still supplying the better one publicly (even using the same name if desired). I think that might be the use case you described.

I do think this could be a useful feature for some of the same reasons. I’m not sure if there are better ways to do it in Swift already.