Currently, there is needed a boilerplate when it comes to protocol conformance especially for generic classes that are used as a box, decorator, etc.
To better visualize the problem take a look at this example:
protocol SomeProtocol {
func someFunction()
}
class ClassA: SomeProtocol {
var test: String = ""
func someFunction() {
print("\(#function)")
}
}
class WeakBox<T: Any> {
private weak var _value: AnyObject?
var value: T? {
return _value as? T
}
init(value: T) {
self._value = value as AnyObject
}
}
let x = WeakBox(value: ClassA())
func dependency(some: SomeProtocol) {
print(some)
}
dependency(some: x) // Argument type 'WeakBox<ClassA>' does not conform to expected type 'SomeProtocol'
WeakBox
of course does not conform to SomeProtocol
as the error message describes.
To fix that currently we use to do:
extension WeakBox: SomeProtocol where T: SomeProtocol {
func someFunction() {
value?.someFunction()
}
}
In case when we have more WeakBox
class usages in a project where protocols need to be adopted there is more and more code needed just to delegate function/variable calls to the underlying implementation.
I'm aware that as the example when e.g. the underlying property is optional
how the auto conforms feature should behave or what kind of syntax we could use to handle it.
I don't have a good candidate, how this could be expressed, so I hope if the community will find this value we will find good approach. Anyway just to start it might look like this:
@autoProtocolConform
extension WeakBox: SomeProtocol where T: SomeProtocol {
var conformer: SomeProtocol: { self._value as! SomeProtocol }
}
I wonder if it would be well received and widely used. What do you think?