In real life, Encoding is nothing but convert data or information in an any intended format, In swift Encoding Protocol does the same. By using the Encoding Protocol, we can convert model data as a request parameter for an API call.

And decoding means converts data into a readable format. In Swift, we can convert JSON data received from web service into our object model. No need to parse data explicitly. We can directly use this model class/struct without parsing the array and dictionaries of the JSON response.
Before implementing encodable and decodable please look into this URL https://reqres.in/api/users, this Url is having JSON response which contains USER data, every operation like calling API and parsing on the same URL.
Before Encodable and Decodable protocol
Before the launch of Encodable and Decodable protocol, SwiftyJSON was on peak in use. Apple launched Codable and Decodable for flexibility in Web API data binding in Swift. Let’s deep dive into how Encodable and Decodable Works.
Encoding:

By using the encoding protocol we can generate request parameters by Model Class / Struct.
Let’s create one instance model by using struct “User“, and conform this struct by Encodable protocol. So we can encode this whole user instance.
1 2 3 4 5 6 7 8 9 |
struct User : Encodable { // conform encodable protocol let userName: String let job: String enum CodingKeys: String, CodingKey { case userName = "name" case job } } |
Coding key enum is used to alter the identity of the User object, Suppose we are eliminating the CodingKey enum block. In User Object user name key will be pass with userName, but by using the coding key enum property we can change and alter from userName to name.
Without use of coding keys: userName : “Rahul”
With use of coding keys: name : “Rahul”
1 2 3 4 5 6 7 |
let user = User(userName: "Rahul", job: "iOS Developer") do { let jsonReq = try JSONEncoder().encode(user) request.httpBody = jsonReq } catch { print(error.localizedDescription) } |
Decoding:

By using the decoding protocol we can convert API response in Model Class / Struct. When done with API call decoding the response in terms of UserResponse object
1 2 3 4 |
struct UserResponse : Decodable { let createdAt : String let id : Int } |
1 2 3 |
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) let userObjects = try JSONDecoder.init().decode(UserResponse.self, from: data) print(userObjects) |
Here is how userObjects will print in the console.
1 2 3 4 |
{ createdAt = "2020-10-29T14:19:58.569Z"; id = 409; } |
Here is full code of encoding and decoding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import UIKit // request structure struct User : Encodable { // conform encodable prtocol let userName,job: String enum CodingKeys: String, CodingKey { case userName = "name" case job } } struct UserResponse : Decodable { let createdAt : String let id : Int } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() webServiceCall() // Do any additional setup after loading the view. } func webServiceCall() { let urlString = String("https://reqres.in/api/users") guard let url = URL(string: urlString) else { return } var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("json/application", forHTTPHeaderField: "Content-Type") let user = User(userName: "Rahul Bandal",job : "iOS developer") do { let jsonReq = try JSONEncoder().encode(user) request.httpBody = jsonReq } catch { print(error.localizedDescription) } URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data, error == nil else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) print(json) let products = try JSONDecoder().decode(UserResponse.self, from: data) print(products) } catch { print(error.localizedDescription) } }.resume() } } |