Associated types are a powerful way of making protocols generic. Generic enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define.
S → Single-responsiblity principle O → Open-closed principle L → Liskov substitution principle I → Interface segregation principle D → Dependency Inversion Principle
-
Single-responsiblity principle (SRP). A class should have only a single responsibility (i.e. changes to only one part of the software’s specification should be able to affect the specification of the class).
-
The Open-Closed Principle (OCP) “Abstraction” Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
- Open for extension: You should be able to extend or change the behaviours of a class without efforts.
- Closed for modification: You must extend a class without changing the implementation.
-
The Liskov Substitution Principle (LSP)“Decorator” objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.
-
Interface Segregation Principle (ISP) Clients should not be forced to depend upon interfaces that they don’t use.
//Wrong Way
//MARK:- Fat Protocol
//Describe the worker actions
protocol WorkerProtcol {
func work() //work
func eat() //eat
}
// Good way
protocol WorkProtcol {
func work() //work
}
protocol EatProtcol {
func eat() //eat
}
- Dependency Inversion Principle (DIP)
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
//===========Abstraction================
protocol DataBaseProtocol
{
func saveToDb(_ item : String)
}
//=============Details=================
//MARK:- Low Level
class CoreDataBase : DataBaseProtocol
{
func saveToDb(_ item : String)
{
//implementation
}
}
//MARK:- High Level
class DataStore
{
// A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
let database : DataBaseProtocol // Abstraction
init(_ database : DataBaseProtocol) {
self.database = database
}
func saveToDb(_ item : String)
{
database.saveToDb(item)
}
}