Concept

Encodable is used to convert Swift models into JSON data.

It is commonly used in POST requests to send structured data to a server.


Key Idea

Swift Model → Encodable → JSON → HTTP Body

Defining a Model

struct RegisterUserRequest: Encodable {
    let name: String
    let email: String
    let password: String
}

The model represents the data to be sent to the server.


JSONEncoder

Used to convert a Swift model into JSON data:

let encoder = JSONEncoder()

Encoding Data

let requestBody = try JSONEncoder().encode(requestModel)

This converts:

Swift object → JSON data