Fetch and decode JSON with async/await and URLSession
modern networking basics.
call URLSession.shared.data(from:) inside an async throws function, check the HTTPURLResponse status, then JSONDecoder().decode([User].self) and let errors propagate via try.
WHAT THIS TESTS This confirms fluency with Swift structured concurrency and Codable, plus disciplined error handling. It is a baseline competency check for any iOS role touching networking.
A GOOD ANSWER COVERS Define an async throws function so both suspension and failure are explicit. Use the async URLSession API: let (data, response) = try await URLSession.shared.data(from: url). This throws on transport failures like no connectivity. Then validate the response by casting to HTTPURLResponse and confirming the statusCode is in the 200 to 299 range, throwing a custom error otherwise, because a 404 or 500 still returns data and would otherwise be decoded as if successful. Decode with let users = try JSONDecoder().decode([User].self, from: data), where User is a struct conforming to Codable whose properties match the JSON, optionally with a keyDecodingStrategy. Errors flow up through try, so the caller wraps the call in do/catch and can distinguish URLError, the custom HTTP error, and DecodingError. Avoid force unwrapping the cast or the URL.
COMMON WRONG ANSWERS Decoding immediately without checking the HTTP status, so error payloads are misread. Force-casting the response or force-unwrapping data. Catching errors and returning an empty array, hiding failures. Mixing completion handlers with async/await unnecessarily.
LIKELY FOLLOW-UPS How do you cancel an in-flight request? Where does Task fit in? How do you map snake_case keys? How would you add a timeout or retry?
ONE CONCRETE EXAMPLE func fetchUsers() async throws -> [User] awaits the data call, guards that the HTTPURLResponse status is in 200..<300 else throws APIError.badStatus, then returns try JSONDecoder().decode([User].self, from: data). The caller writes do { let users = try await fetchUsers() } catch { handle the error }, cleanly separating success from each failure category without force unwraps.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.