Swift Closet
Published in

Swift Closet

Protocols! Why and How in iOS Application Development?(My Story )

In this Article I am not going to dig into Definition, Just let you know my story related to Protocols.

Note: I am still learning the below are scenarios where I use protocols. Protocols are very vast to use.

Lets start …

"a protocol defines a blueprint of methods or properties that can then be adopted by classes (programiz.com).

Ok got the Definition by how would I use this in Mobile App Development.
So I got an Opportunity to work with a Sr. Developer, I learned and I used in many ways among them 3 scenarios I would Like to share which can help My Fellows.
1. ViewModels
2. Some Generic Helpers (Parsers, Validators e.t.c)
3. TestCases

Scenario 1:
We are using MVVM, and suppose I took your code and created a new View Model of any Controller with existing ViewModel. Now What things should I have to change?

  1. Bindings: Like how VM interacts with VC. New VM must have its own method.
  2. Functions/Methods
  3. And main thing the Reference of ViewModel everywhere.

So What is the Solution to make it Abstract? Here I came to know Protocols can do much more just to be used in Tableview cell for interaction.

let’s Look into Code,

protocol SampleViewModelType{//Propertiesvar id: Int? {get set}
var name: String? {get set}

Above is a Protocol, defining Type of ViewModel. Or you can say How will the ViewModel will look like of the SampleViewController. (We’ll later sagregate the protocols).

Now, Implement this protocol

class SampleViewModel: SampleViewModelType{ var id: Int? var name: String? func fetchData() {}}

Let’s Create a ViewController,

class SampleViewController{ var viewModel: SampleViewModelType? func didload(){

Above you can see the reference is created with type of protocol. Now Its defined in controller that the ViewModel of this Controller should have implemented this Protocol.

Because of this the Properties and functions used in ViewModel doesn’t need to change even ViewModel get changed.

Last Part Segregation of SampleViewModelType Protocol,

protocol SampleViewModelActionType{  func fetchData()}protocol SampleViewModelPropertyType{  var id: Int? {get set}
var name: String? {get set}
SampleViewModelType: SampleViewModelActionType, SampleViewModelPropertyType{}

Please check my next publication for further Scenario.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Syed Rafay

Syed Rafay

IOS Developer - Former Firefox Club Captain - Tech Nerd - Towards Algo Expert - Just Code, Eat and Sleep