Member-only story
Writing a Network Layer in Swift: Protocol-Oriented Approach

In this guide we’ll look at how to implement a network layer in pure Swift without any third-party libraries. Lets’ jump straight to it! After reading the guide, our code should be:
- protocol-oriented
- easy to use
- easy to implement
- type safe
- use enums to configure endPoints.
Below is an example of what we’ll ultimately achieve with our network layer:
By just typing router.request(. with the power of enums we can see all the endPoints that are available to us and the parameters needed for that request.
First, Some Structure
When creating anything it is always important to have structure, so it will be easy to find things later on. I’m a firm believer that folder structure is a key contributor to software architecture. To keep our files well organised let’s create all our groups beforehand and I will make note of where each file should go. Here is an overview of the project structure. (Please note names are only suggestions, you can name your classes and groups whatever you prefer.)
EndPointType Protocol
The first thing that we need is to define our EndPointType protocol. This protocol will contain all the information to configure an EndPoint. What is an EndPoint? Well, essentially it is a URLRequest with all its comprising components such as headers, query parameters, and body parameters. The EndPointType protocol is the cornerstone of our network layers implementation. Go ahead, create a file and name it EndPointType. Place this file in the Service group. (Not the EndPoint group, this will be made clearer as we continue).