MasterOnce
HomeBlogHow-To
3 min readFeb 23, 2026
Swift

How to Decode JSON with Codable

Parse JSON into Swift types.

Steps

  1. Paste the code into a Swift file or playground.
  2. Run it once to verify the output.
  3. Adjust the inputs to match your use case.

Copy and paste

import Foundation

struct User: Codable {
    let id: Int
    let name: String
}

let data = "{"id":1,"name":"Ava"}".data(using: .utf8)!
let user = try JSONDecoder().decode(User.self, from: data)
print(user)

Notes

  • Keep functions small and focused for reuse.
  • Prefer safe APIs like optionals and guards.