Build: User List
This screen fetches a list of users from a JSON string and shows their names in a list.
Target UI
--------------------- | User List | --------------------- | * Alice | | * Bob | | * Charlie | ---------------------
--------------------- | User List | --------------------- | * Alice | | * Bob | | * Charlie | ---------------------
import SwiftUI struct UserListView: View { @State private var users: [User] = [] @State private var isLoading = true var body: some View { VStack { Text("User List") .font(.title) .padding() if isLoading { Text("Loading users...") } else { List(users, id: \.id) { user in Text(user.name) } } } .onAppear { // TODO: Parse JSON and update users } } } // TODO: Define User struct here struct UserListView_Previews: PreviewProvider { static var previews: some View { UserListView() } }
import SwiftUI struct User: Codable, Identifiable { let id: Int let name: String } struct UserListView: View { @State private var users: [User] = [] @State private var isLoading = true let jsonString = "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"},{\"id\":3,\"name\":\"Charlie\"}]" var body: some View { VStack { Text("User List") .font(.title) .padding() if isLoading { Text("Loading users...") } else { List(users) { user in Text(user.name) } } } .onAppear { if let data = jsonString.data(using: .utf8) { do { let decodedUsers = try JSONDecoder().decode([User].self, from: data) users = decodedUsers } catch { print("Failed to decode JSON: \(error)") } } isLoading = false } } } struct UserListView_Previews: PreviewProvider { static var previews: some View { UserListView() } }
We defined a User struct that conforms to Codable and Identifiable so SwiftUI can uniquely identify each user in the list.
Inside onAppear, we convert the JSON string to Data and use JSONDecoder to decode it into an array of User objects.
We update the users state with the decoded array and set isLoading to false to show the list.
This approach cleanly parses JSON and updates the UI reactively.
--------------------- | User List | --------------------- | * Alice | | * Bob | | * Charlie | ---------------------
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