I am using Swift and am wondering about the concepts of Extension and Delegation. Recently I found a case where either one of these two concepts could be applied. This reminded of the "composition over inheritance" principle, which teaches that a "has-a" relationship may be preferred to a "is-a" relationship.
I encountered a case where it is always an object of some specific type that depends on an object conforming a certain protocol, therefore allowing both Extension and Delegation to be used.
For instance, I have a UIViewController that depends on a subclass of UIView. Say we take the following protocol:
protocol ViewInteraction {
func interact()
}
This protocol will be conformed by the UIView subclass, say InteractedView
. And any UIViewController
may need to interact with this InteractedView
.
In these types of situations, what's a good default - the Delegation pattern, or the Extension pattern? That is, should I use the Delegation pattern - letting the InteractedView
conform it, and letting the UIViewController
subclass manipulate a ViewInteraction
property - or should I follow the Extension pattern and extend UIViewController
to conform the ViewInteraction
protocol (and call the InteractedView
)?