Is it possibel to create a class that conforms to protocols without clients of this class knowing about this coformance?
I want o achieve what I would achien in Objective-C by adding in the .m file the following code:
// .m file @interface MyClass () <SomeProtocol> @end
How to do this in Swift?
The following gives me an error:
"'Private' modifier cannot be used with extensions that declare protocol conformances."
private extension MyClass: SomeProtocol { } public class MyClass : NSObject { }
I assume since you say "when attempting to build" that the compiler is crashing – that is definately something you should file, as The Compiler Should Never Crash™ 🙂.
I don't have any special insight into why Swift doesn't allow private conformance, but I do have extensive experience these types of issues in larger source bases. The biggest thing I've noted about private conformance, especially amonst classes that are meant to be subclassed further, is that you often end up with conflicting implementations.
For example, you have a class that privately conforms to a protocol and implements all of its methods. Later a subclass comes along and wants to do the same, but only wants to implement the required methods (because the optional ones not being implemented might provide some default behavior that subclass wants). But now you have 2 problems:
1) The object expecting this protocol implementation now has possibly 2 consumers of the protocol on the same object. This leads to both objects having to guard against unexpected calls. Or none, as due to the private conformance, the subclass can't call super to resolve the unexpected calls.
2) There is no way for the subclass to get the behavior it wants without modifying the protocol, as the superclass's implementation can't be removed without affecting its behavior either.
Overall the private class that calls back up to its owning class solves these issues by ensuring that only the exact implementation as desired is used for the delegate, and by virtue of being a private class it cannot be externally subclassed either. Similarly if you have a number of classes that might want to share the logic of this private class, you can instead make it internal and share the common logic, which is a lot easier than reimplementing that logic in each class that wants to conform to that delegate.
Overall it is harder to do than simply provide private conformance, and in many cases this is way overkill for what you want to do.
HTH.