Generic Service Layer with Codable & Result type Swift 5

Joyal Clifford
2 min readDec 9, 2019

When we begin with a new project always think about unique network layer long with simplicity, extendability and customizability.

I always believe pure code developed by own/team rather than third party Library. That makes us easy to know in and out each stage of development.

Now it’s time to create own layer that must be generic & light-weight in usage. Here I would like to show by calling API https://newsapi.org/ .

Result Type

Swift 5 come up with Result type as Generic Enumeration, with a value that represents either a success or a failure, including an associated value in each case.Result<Success, Failure>

In our case, we need to get the Generic model as a success result

Result<T,NetworkError>

where the response type Result

switch response {case .success(let model): // success taskcase .failure(let error): //failure task}

When we are dealing with VIPER or clean Arch we will focus on the service layer that will communicate with Network API like URLSession. Alway when hitting REST API we need to send request Parm and result as data to JSON serialization. Those enter task we can be done in just 3 customizable components

Prepare Codable Model in 30'Sec

It’s time to jack port from JSON to Codable model class by swift Codable protocol. Codable is a type alias for the Encodable and Decodable protocols. When you use Codable as a type or a generic constraint, it matches any type that conforms to both protocols.

typealias Codable = Decodable & Encodable

Here I would like to give some tricks that help every developer easiest way to create JSON into Model class by using the online parser like https://www.json4swift.com/ It will reduce maximum pain.

Prepare Service Layer

Major Job is to prepare Network API like It’s important to know that a request is made up of four things:

  1. The endpoint
  2. The method
  3. The headers
  4. The data (or body)

Finally, create an intermediate API that takes RequestModel & Decodable as result.

Now time to see the usage of Service layer API

We can see here TodaysNews.self is Decodable model & Result contains success case contain Decodable object type of TodaysNews. In other case Fail contain Network Error Type.

Final conclusion

Here we need to pass every time Decodable model along with Request param. so it’s easy to handle thinks & testability will increase. This task did in VIPER Arch with Generic Service layer. Find the source code here: Github.

📌 Find me on LinkedIn and Twitter here. 😄

--

--

Joyal Clifford

Developer by heart | Swift | Objective-C | Learner | Creative | Blogger