iOS Clean Code Architecture with RxSwift and Swinject
Having a codebase that is managed, structured, clean and scalable and will be very helpful as your codebase grows and features keeps on getting added in your application. So, in this we are going to setup our iOS project following Clean Code Architecture using RxSwift and we’ll be using Swinject for dependency injection.
So, let get on with it.
1. First create a new Xcode project. We are going to use Swift Package Manager to add libraries in our project.
We are going to add these libraries in our project.
- RxSwift
- Swinject
- RxAlamofire — This is for performing network requests.
- LBTATools — This is for creating views programmatically.
2. Now, we are going to setup our business logic layer. I’ve created a New Group named Core. We add Domain and Data Group inside it which will contain our Repo, UseCases, RepoImpl and ViewModels.
3. In this project, we are going to fetch nationality and profile details. We are going to get nationality name from nationality API matching nationality ID from profile API.
If you want to check responses here are the hosted nationality and profile APIs I’ve hosted these in github for demo purposes.
Nationality API: https://gist.githubusercontent.com/nabs107/a03185d236a19f1b97d23c3fc0ce9b8d/raw/16725042e8e5f8fbf8a6986b2824b708a8d8396c/nationality.json
We get nationality from profile API which is an id. So, we are going to match the id with the response from Nationality API and get the name.
4. Let’s create Model classes first.
5. Let’s create Repo now. It will be a protocol that will have a concrete implementation.
6. Let’s create Network class that will have GET / POST requests.
7. Now we are going to create implementations of above repos.
8. Now we create the UseCases for Profile and Nationality.
9. Finally, we are going to create ViewModels for nationality and profile.
10. Now we are done with the business logic layer. Let’s implement Swinject in our project to create dependencies of business logic layer. Look into the documentation of Swinject for its implementation. It’s very easy to understand.
We are going to create a container variable in AppDelegate.swift which will hold all the instances of dependencies we need in our project.
To access container variable in any ViewController, we are going to create extension of UIViewController and add variables like below.
11. Now, we can work on our ViewController class.
Here, is a gif of the screen that fetches nationality and profile details and shows the nationality name in the screen.
Here’s the link to the demo project.
If you like this article, feel free to show your support by clapping on the article.