Adapter design pattern in Swift

“Adapter converts class protocol for other, expected by client. Adapter allows to objects to cooperate with objects they could not normally work with due to different protocols.”

Today we will implement the Adapter design pattern in Swift with a simple playground example. Imagine, we have a Cassette class that conforms the MusicPlayer protocol as bellow:

Now we have a new InternetMusicPlayer protocol that be declared as bellow:

Now we want the Cassette class conforms the InternetMusicPlayer protocol without any code changes, we will implement the Adapter design pattern as bellow:

The new CassetteAdapter class declares a variable named cassette that gets Cassette value from the designed initializer. Because the CassetteAdapter class adopts the InternetMusicPlayer protocol so it must implements 2 methods: downloadMedia & play.

The downloadMedia function call the insertMedia function of cassette variable, The play function call the play function of cassette variable as well.

Now you can see, the Adapter design pattern converts the MusicPlayer protocol to the InternetMusicPlayer protocol for the Cassette class by create a new CassetteAdapter class. We can even implement the Adapter design pattern by simpler way as bellow:

That’s all! It’s a simple playground example & easy to understand how Adapter design pattern works in Swift. Please leave your comment if you have any concerns.

Thanks!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade