From the course: Practical Design Patterns in Swift

Working with incompatible interfaces - Swift Tutorial

From the course: Practical Design Patterns in Swift

Start my 1-month free trial

Working with incompatible interfaces

- [Instructor] There are cases where we have to use a type that doesn't fit well into the rest of the software system. Situations like this might occur when we use code that we don't own like for example, third party libraries or legacy code. We can't modify anything in the incompatible interface but we don't want to refactor our existing code either. So, how can we make the incompatible interface work with the rest of our code? The adapter pattern comes to the rescue. In this typical implementation, it wraps the object to be adapted and exposes the interface that's familiar to the caller. The caller uses the adapter, which, in turn, converts the cause was that makes sense to the adapted type. The adapter returns the results to the caller through the compatible interface. Swift type extensions make it even easier to implement the adapter pattern. We don't need to introduce a wrapper type. Instead, we extend the type and add the required methods and calculated properties to that extension. This technique works without modifying the types of original implementation and that's precisely the behavior we need. The adapter lets us integrate a type with an incompatible interface into our software. The type's interface gets converted to another interface to make it work with the rest of the system. The adapter doesn't have any drawbacks. One common mistake is trying to adapt an interface that doesn't provide the expected functionality. So, before you start implementing the adapter, make sure that you're using the right component.

Contents