11.8. Decluttering codes from View Controller (Recommended Read)
If you noticed, we have 281 lines of code in ViewController.swift. It appears to be a jumble of code. And in many ways, it's hard to read when you'll return to it after a week.
We can utilize protocols and extensions to break the code into multiple files, making it more modular.
Separating the API calls from the Controller
Let's first separate the code we used to call the Contacts API. The methods we have related to the Contacts API are:
getAllContacts()
addANewContact(contact: Contact)
getContactDetails(name: String)
Defining a Protocol for the API Calls
So, let's write a protocol where we will declare the methods we will use to call the Contacts API. Let's create a new Swift file ContactsProtocol.swift, inside the 'Contact API Configs' folder.
//
// ContactsProtocol.swift
// App11
//
// Created by Sakib Miazi on 5/29/23.
//
import Foundation
protocol ContactsProtocol{
func getAllContacts()
func addANewContact(contact: Contact)
func getContactDetails(name: String)
}Adopting the Protocol
Awesome, now that we have a protocol, let's create another Swift file, ContactsAPICalls.swift, in the MainScreen folder. Import UIKit and Alamofire in this file. Let's write the following code in the file:
In the above code, we use the extension magic to adopt the ContactsProtocol from ViewController. Now, it's time to move the methods from ViewController.swift to ContactsAPICalls.swift.
The file structure of the project now looks like this:

Now, the code is more modular and more manageable.
Note: You can make it even more modular by putting the table view protocol codes into a separate file from the ViewController.
Last updated
Was this helpful?