Turn an incompatible object into a target interface or class using a real world example and adapter design pattern in Swift.
Fist of all, let me emphasize that this is the real world representation of what we are going to build this little Swift adapter pattern guide:
USB C to USB Adapter
] Adapter is a structural design pattern that allows objects with incompatible interfaces to work together. In other words, it transforms an object's interface to customize it to another object.
So the adapter can turn one thing into another, sometimes called the wrapper because it breaks the object and provides a new interface around it. It's like a software dongle for specific interfaces or older classes. (Dongle haters: it's time to leave the past!) 😂
Adapter design pattern implementation
Creating an adapter in Swift is actually a super easy task to do. You only need to create a new object, "box" the old one into it and implement the necessary interface on the new class or structure. In other words, a wrapper object will be our adapter to implement the target interface by wrapping another adaptee object. Then again:
The item we adapt to a specific goal (eg USB-A port at primary school).
An item that breaks the original and produces the new requirements
It is the object we want to use adaptee with (USB-C connector).
How to use the Swift Adapter Pattern?
You can use an adapter if you want to integrate a third party library into your code, but the interface does not match your requirements. For example, you can create a wrapper around an entire SDK or backend API endpoints to create a common denominator. 👽
In my example, I will pack an EKEvent object with an adapter class to implement a completely new protocol. 📆
Another usage case is when you need to use more existing final classes or structures, but they lack some functionality and you want to build a new target interface on top of them. Sometimes it's a good choice to implement a wrapper to handle this messy situation. 🤷♂️
It's about the adapter design pattern. Generally, it's very easy to implement it in Swift ̵