Component - Codable protocol for JSON parsing
This UI component demonstrates how to use the Codable protocol in Swift to parse JSON data into native Swift structs. It shows a simple list of user names loaded from JSON and displayed on screen.
This UI component demonstrates how to use the Codable protocol in Swift to parse JSON data into native Swift structs. It shows a simple list of user names loaded from JSON and displayed on screen.
NavigationView
└── List
└── Text (for each user name)Codable protocol in Swift help you do?Codable protocol is designed to simplify converting data between Swift objects and external formats like JSON.Codable protocol explicitly.{"id": 10, "title": "Book"}struct Item: Codable { var id: Int; var title: String }item.title after decoding?title and 10 to id.let json = "{\"name\": \"Alice\"}".data(using: .utf8)!
struct Person: Codable { var name: String }
let person = try JSONDecoder().decode(Person.self, from: json){"user": {"id": 1, "name": "Bob"}}struct User: Codable { var id: Int; var name: String }
struct Response: Codable { var user: User }Response object?Pass the test and this pattern moves unknown