1 min read

Guide to Interface Segregation Principle in Swift

Guide to Interface Segregation Principle in Swift
Photo by Kelly Sikkema / Unsplash

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. It states that clients should not be forced to depend on methods they do not use. In other words, interfaces should be designed in such a way that clients can use only the methods that are relevant to them.

When a class implements an interface, it is expected to implement all the methods defined in the interface, even if it does not need them. This can lead to unnecessary dependencies between classes and can make the code harder to maintain and change.


Let's look at an example to illustrate the Interface Segregation Principle in Swift:

protocol Printer {
    func print()
    func scan()
    func fax()
}

class OfficePrinter: Printer {
    func print() {
        // Code to print a document
    }
    
    func scan() {
        // Code to scan a document
    }
    
    func fax() {
        // Code to send a fax
    }
}

In the above example, the Printer protocol has three methods: print(), scan(), and fax(). The OfficePrinter class implements all three methods, even though it may not need them all. This violates the Interface Segregation Principle, as clients who only need to print documents may be forced to depend on the scan() and fax() methods.

To follow the Interface Segregation Principle, we can split the Printer protocol into smaller, more specific protocols:

protocol Printer {
    func print()
}

protocol Scanner {
    func scan()
}

protocol Fax {
    func fax()
}

class OfficePrinter: Printer {
    func print() {
        // Code to print a document
    }
}

class MultiFunctionPrinter: Printer, Scanner, Fax {
    func print() {
        // Code to print a document
    }
    
    func scan() {
        // Code to scan a document
    }
    
    func fax() {
        // Code to send a fax
    }
}

Now we have three separate protocols, each with a single responsibility. The OfficePrinter class only implements the Printer protocol, while the MultiFunctionPrinter class implements all three protocols. This makes it easier for clients to use only the methods they need and reduces unnecessary dependencies.

By following the Interface Segregation Principle, we can create more modular, maintainable code that is easier to test and change over time.