JSON ยท SWIFT RECIPE

Decode JSON into a Swift type

Replace untyped dictionaries with a Decodable model.

main.swift
import Foundation
struct Developer: Decodable {
    let name: String
    let languages: [String]
}
let json = #"{"name":"Sam","languages":["Swift","Rust"]}"#
do {
    let person = try JSONDecoder().decode(Developer.self, from: Data(json.utf8))
    print(person.name)
    print(person.languages.joined(separator: ", "))
} catch { print("Decoding failed: \(error)") }

How it works

Decodable supports compiler-synthesized decoding for stored properties that are also decodable. JSONDecoder validates required keys and field types. Preserve errors so you can diagnose mismatched data.

EXPECTED OUTPUT
Sam
Swift, Rust

Keep in mind

Use CodingKeys for mismatched names. Make fields optional only when missing or null is valid.

Read the Swift language reference