3 min readFeb 23, 2026
SwiftHow to Decode JSON with Codable
Parse JSON into Swift types.
Steps
- Paste the code into a Swift file or playground.
- Run it once to verify the output.
- 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.
