0
0
Ios-swiftHow-ToBeginner ยท 4 min read

How to Use Codable in Swift for Easy Data Encoding and Decoding

In Swift, use Codable to make your data types encodable and decodable for formats like JSON. Simply conform your struct or class to Codable, then use JSONEncoder and JSONDecoder to convert between your model and JSON data.
๐Ÿ“

Syntax

To use Codable, declare your struct or class to conform to it. This automatically combines Encodable and Decodable protocols.

Use JSONEncoder to convert your model to JSON data, and JSONDecoder to convert JSON data back to your model.

swift
struct User: Codable {
  var name: String
  var age: Int
}

let encoder = JSONEncoder()
let decoder = JSONDecoder()
๐Ÿ’ป

Example

This example shows how to encode a User struct to JSON and decode JSON back to a User instance.

swift
import Foundation

struct User: Codable {
  var name: String
  var age: Int
}

let user = User(name: "Alice", age: 30)

// Encode User to JSON
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
if let jsonData = try? encoder.encode(user) {
  if let jsonString = String(data: jsonData, encoding: .utf8) {
    print("Encoded JSON:\n\(jsonString)")
  }

  // Decode JSON back to User
  let decoder = JSONDecoder()
  if let decodedUser = try? decoder.decode(User.self, from: jsonData) {
    print("Decoded User: \(decodedUser.name), age \(decodedUser.age)")
  }
}
Output
Encoded JSON: { "name" : "Alice", "age" : 30 } Decoded User: Alice, age 30
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Not conforming all nested types to Codable.
  • Mismatched property names between your model and JSON keys.
  • Forgetting to handle optional properties properly.
  • Not using try with encode and decode, which can throw errors.

Use CodingKeys enum to map JSON keys if they differ from your property names.

swift
struct Person: Codable {
  var firstName: String
  var lastName: String

  enum CodingKeys: String, CodingKey {
    case firstName = "first_name"
    case lastName = "last_name"
  }
}

// Wrong: JSON keys don't match properties
// let json = "{\"firstName\": \"Bob\", \"lastName\": \"Smith\"}" // This will fail

// Correct: Use CodingKeys to map JSON keys
let json = "{\"first_name\": \"Bob\", \"last_name\": \"Smith\"}"
๐Ÿ“Š

Quick Reference

Codable Cheat Sheet:

  • struct MyType: Codable {} - Make your type codable.
  • JSONEncoder().encode(instance) - Convert to JSON data.
  • JSONDecoder().decode(Type.self, from: data) - Convert JSON data to model.
  • Use CodingKeys to map JSON keys if needed.
  • Handle errors with try and catch.
โœ…

Key Takeaways

Conform your data types to Codable to enable easy JSON encoding and decoding.
Use JSONEncoder and JSONDecoder to convert between your models and JSON data.
Match your property names with JSON keys or use CodingKeys to map them.
Always handle encoding and decoding errors with try and catch.
Ensure all nested types also conform to Codable for successful encoding/decoding.