How do I decode paginated API responses in Swift?

When working with paginated API responses in Swift, it's essential to handle the data correctly to ensure a smooth user experience. Pagination typically involves requesting a set number of records and then using pagination tokens or page numbers to fetch additional sets of records as needed.

Here's a basic example of how you can decode a paginated API response in Swift. This example uses the `Codable` protocol and demonstrates how to manage pagination effectively.

struct PaginatedResponse: Codable { let data: [T] let nextPage: String? } struct Item: Codable { let id: Int let name: String } func fetchItems(page: String? = nil, completion: @escaping ([Item]) -> Void) { var urlString = "https://api.example.com/items" if let page = page { urlString += "?page=\(page)" } guard let url = URL(string: urlString) else { return } let task = URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, error == nil else { print("Error fetching data: \(String(describing: error))") return } do { let paginatedResponse = try JSONDecoder().decode(PaginatedResponse.self, from: data) completion(paginatedResponse.data) } catch { print("Failed to decode JSON: \(error)") } } task.resume() }

pagination API Swift Codable networking