Adapter Pattern (Swift)
Adapter is a structural design pattern, Let’s understand it with real world example:
Suppose you have old iPhone earphone and you have new iPhone with support for older earphone removed. How you can use old earphones now?
Solution will be you buy an Jack adapter which will provide an interface or method or way through which earphone can work with earphones.

Here In this example
old iPhone earphone : Adaptee
Jack adpater: Adapter
In programming world, adaptee is old class which is not compatible with new protocol.
We can implement adapter pattern in two ways. The first one is object adapter which uses composition. There is an adaptee instance in adapter to do the job like the following figure and code tell us.
Using Compostion technique, in which Adapter will contain adaptee and adapter implements Target.
//Slot is a iPhone Charger slot
protocol Slot{
func insert70.9MM()
}//Adapter can adopt and conform to Slot....
class Adapter: Slot{
//Composition of Adaptee
var adaptee: Adapteeinit(adaptee: Adaptee) {
self.adaptee = adaptee
}func request() {
adaptee.specificRequest()
}
}class Adaptee {
func specificRequest() {
print("Specific request")
}
}// usage
let adaptee = Adaptee()
let adapter = Adapter(adaptee: adaptee)
adapter.request()
In this example suppose adaptee cannot implement or adopt to
Slotprotocol directly, then what we have done is we have make a bridge between adaptee and Target through Adapter and it will simulates like adaptee can access protocol method request.
Now take another very common example of adapter pattern which uses delegation.
ViewController has a CollectionView and CollectionView have custom cell let say MyCell.Swift class and MyCell have a button. On click of which we want ViewController which contains CollectionView to change some behaviour let say change color of it’s background or change theme.
So, This is very common mechanism to have a protocol with function cellClicked(). Now, using this protocol MyCell can communicate or pass message via cellClicked() to ViewController that i have been clicked by user. You can do your stuff now….
Now can you identify which is what?
………
Here MyCell cannot communicate directly with ViewContoller so it takes adapter helps which is protocol with method cellClicked().
Adapter : Protocol with method cellClicked
Adaptee:MyCell
Destination/Target:ViewController.
Another way to do this is using multiple inheritance i.e. Adapter can have both Adaptee and Target.
protocol Target {
func request()
}class Adaptee {
func specificRequest() {
print("Specific request")
}
}class Adapter: Adaptee, Target {
func request() {
specificRequest()
}
}// usage
let tar = Adapter()
tar.request()
