VIPER Architecture Swift iOS

Raghav Sharma
2 min readApr 24, 2021

--

What is VIPER

Entity.It is similar to the model layer in the other architectures.

View. it sends actions of user to the presenter and display data accordingly.

Presenter. Its gets the data from the interactor , send that model data to the View which displays the data accordingly.

Interactor. it contains the main business logic required. The interactor fetches data from the entity or model. We have used single responsibilities principle to segregate buisness logic from UI layer.

Router. It primary function is to navigate between different view controllers.

IMPLEMENTATION

Here i have tried to implement a basic use case for Order Screen. I have tried to add label and pass text to that label using VIPER architecture in swift

// Entity

struct OrderEntity {

var title: String

}

//View

protocol OrderViewing: class {

func updateTitle(orderEntity: OrderEntity)

}

class OrderViewController: UIViewController {

@IBOutlet weak var orderTitleLabel: UILabel!

var presentor: OrderPresenting!

override func viewDidLoad() {

presentor.onViewDidLoad()

}

}

extension OrderViewController: OrderViewing {

func updateTitle(orderEntity: OrderEntity) {

orderTitleLabel.text = orderEntity.title

}

}

//Presenter

protocol OrderPresenting {

func onViewDidLoad()

}

class OrderPresenter {

weak var view: OrderViewing?

var interactor: OrderInteracting?

var router: OrderRouting?

init(view:OrderViewing, interactor: OrderInteracting, router: OrderRouting) {

self.view = view

self.interactor = interactor

self.router = router

}

}

extension OrderPresenter: OrderPresenting {

func onViewDidLoad() {

guard let orderEntity = self.interactor?.getEntityData() else {return}

DispatchQueue.main.async {

self.view?.updateTitle(orderEntity: orderEntity)

}

}

}

//Interactor

protocol OrderInteracting {

func getEntityData() -> OrderEntity

}

class OrderInteractor {

}

extension OrderInteractor: OrderInteracting {

func getEntityData() -> OrderEntity {

let orderEntity = OrderEntity(title: “Order”)

return orderEntity

}

}

// Router

protocol OrderRouting {

}

class OrderRouter {

var view: UIViewController?

init(view: UIViewController) {

self.view = view

}

}

extension OrderRouter: OrderRouting {

}

//Builder

class OrderBuilder {

static func buildOrderModule() -> UIViewController {

let view = OrderViewController()

let interactor = OrderInteractor()

let router = OrderRouter(view: view)

let presenter = OrderPresenter(view: view, interactor: interactor,router: router)

view.presenter = presenter

return view

}

}

please feel free to drop off any suggestions and improvements.

please find me below on LinkedIn and GitHub

https://github.com/raghav1786

--

--

Raghav Sharma
Raghav Sharma

Written by Raghav Sharma

Software engineer - iOS @ Y Media Labs

No responses yet