Although the Swift docs talk a lot about delegation, I can't seem to find an example of making a type conform to a protocol by delegation, and whether it's possible to do this compactly. Instead the examples of "delegation" I find are when the delegate handles some other set of responsibilities.
For example, lets consider the following code:
protocol Proto1 {
func doX()
func doY()
}
struct Struct1 {
let delegate: Proto1
func doZ(){
print("Z")
}
}
extension Struct1: Proto1 {
func doX() {
return self.delegate.doX()
}
func doY() {
return self.delegate.doY()
}
}
struct Proto1Delegate: Proto1 {
func doX() {
print("Delegate X")
}
func doY() {
print("Delegate Y")
}
}
let s1 = Struct1(delegate: Proto1Delegate())
s1.doX()
s1.doY()
s1.doZ()
So what I've done here, is I've extended Struct1
to conform to Proto1
simply by delegating (via composition) the requirements of Proto1
to the delegate of Struct1
.
This code works, but it's a bit unfortunate that in the extension I had to explicitly implement each requirement by handing off the delegate. It would be far nicer if I could simply declare that the extension is handled by a delegate. For example, I'd love to be able to do something like this for the extension:
extension Struct1 : Proto1 by delegate
thereby removing the boilerplate. Kotlin (a very similar language) has this kind of support that you can read about here. Does Swift have similar functionality, or are the plans to add such support?