Adapter design pattern in Swift

Steve Dao
1 min readJul 24, 2017

“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!

--

--