Interface Segregation Principle in Swift (with code examples) — SOLID Principles

Gizem Türker
2 min readJul 19, 2022

--

“Clients should not be forced to depend upon interfaces that they do not use.”

It’s easy to violate any of the principles. Similar to the single responsibility principle, the purpose of the interface segregation principle is to make our software project more functional and valuable by dividing it into multiple independent parts.

Why do we need LSP?

ISP helps us to avoid some threads:

  • Fat interfaces
  • don’t force classes to implement methods they can’t
  • don’t pollute protocols with a lot of methods

Let’s create classical example we have a Worker a struct with two methods and a Manager struct that has a manage(worker: Worker) method:

The manager bought a Robot to make things easier and thought he could get more output if he worked with workers. Let’s see what changes in this situation:

(Bad) Example

Here is what will not use the sleep function used forHuman andRobot. Therefore, what need not include the new method here. Because nd this is what Interface Segregation is all about: clients should never implement interfaces they don’t use, and, right now, the Robot struct is being forced to implement the sleep method.

(Better) Example

We adapted the protocols to our structure. We implemented new protocols for Human andRobot. In this example, explain how I use protocols to make my code clean, manageable and testable.

A good example of interface segregation in the iOS SDK is Codable. The definition of Codable is as below:

typealias Codable = Decodable & Encodable

This was the fourth article of the series of five about SOLID and its use in Swift. I hope you have enjoyed it.

Discuss in the comment.

Follow the LinkedIn, Twitter, and Github.

--

--