Swift Generic Service

Hello friends, in this article we will talk about how to create a generic service with Swift. With a generic service structure, we can easily change and manage it when we change something extra in the future. We can make service requests with less code.

In the application where we list music, movies, applications and books from Apple’s services, we wrote a different function for each request. It may seem logical to use it in applications with low service requests, but there is no guarantee that it will not grow in the future. So let’s make the service structure of this project generic. The current state is as follows.

Now we will divide our service structure into 3 different classes. These; APIConstants class where constant variables are kept, APIRouter which has enum structure which requests to be thrown, and Services class where service request is thrown generically.


In this class, there are urls in general and what will go when sending the request.


Our structure here is completely enum. When we create a new request, we can add it here as a case, and then we need to determine which method to send, which token value to get, which url to go to, which parameters to take.

As an example, I have added a structure that takes parameters and has different methods. You can go over this.


In this class, we will create a generic function and throw every request through this generic function. I will create a variable named shared with a singleton and proceed over this variable.

When sending a request, I send it as follows.

If you have questions, you can reach us by sending an e-mail or comment. You can access the project here. You can find more articles here.

Good work.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.