Swift 6 · Types and protocols
Encode and decode JSON
Conform to Codable and use JSONEncoder and JSONDecoder.
struct User: Codable {
let id: Int
let name: String
}
let data = try JSONEncoder().encode(User(id: 1, name: "Ada"))
let user = try JSONDecoder().decode(User.self, from: data)
Official Swift 6 documentation