Skip to Content
Course content

129: Practice Exercise: Building a Type-Safe Networking Layer with async/await

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I remember the first time I tried to build a "universal" networking client in Swift. I wanted one single function that could handle every API call in my app so I wouldn't have to write the same URLSession boilerplate over and over. I thought I had it figured out using generics, but I ran into a compiler error that felt like a riddle. Here is the kind of code I wrote back then—and the kind of mistake I still see developers make today.

struct NetworkManager {
    func fetchData(from url: URL) async throws -> Decodable {
        let (data, _) = try await URLSession.shared.data(from: url)
        return try JSONDecoder().decode(Decodable.self, from: data)
    }
}

// Trying to use it:
let user = try await manager.fetchData(from: userURL)
print(user.username) // ❌ Compiler Error: Value of type 'Decodable' has no member 'username'

The Decodable Return Type Trap

At first glance, this looks logical. I told Swift that the function returns something that conforms to Decodable, and I'm using JSONDecoder. But here is the problem: Decodable is a protocol, not a concrete type. When you declare the return type as Decodable, you're telling the compiler, "I'll give you back something that can be decoded, but I'm not telling you what it actually is."

By the time the data reaches your variable user, Swift has "erased" the specific type. It knows it's Decodable, but it doesn't know it's a User object. That's why you can't access .username—the protocol Decodable doesn't have a username property; only your specific User struct does.

Returning the Generic Type T

To fix this, we need to use a generic placeholder. Instead of returning the protocol, we define a generic type T and constrain it to Decodable. This tells Swift: "This function will return a specific type that the caller decides, as long as that type knows how to decode itself."

struct NetworkManager {
    // We introduce  here
    func fetchData<T: Decodable>(from url: URL) async throws -> T {
        let (data, response) = try await URLSession.shared.data(from: url)
        
        // We ensure the response is actually a 200 OK
        guard let httpResponse = response as? HTTPURLResponse, 
              httpResponse.statusCode == 200 else {
            throw URLError(.badServerResponse)
        }
        
        return try JSONDecoder().decode(T.self, from: data)
    }
}

// Now, we tell Swift what T is by providing the type annotation
let user: User = try await manager.fetchData(from: userURL)
print(user.username) // ✅ Works!

Notice the difference? By returning T, we preserve the type identity. When you call the function and specify let user: User, Swift infers that T is User, and the JSONDecoder now knows exactly which model to map the JSON onto.

Handling API Errors Gracefully

In a real-world app, URLError or DecodingError are a bit too generic. If the API returns a 404 or a custom "Invalid API Key" JSON body, you want your UI to reflect that. I usually recommend wrapping your networking logic in a custom Error enum to keep the call site clean.

enum NetworkError: Error {
    case invalidResponse
    case decodingFailed
    case serverError(Int)
}

struct NetworkManager {
    func fetchData<T: Decodable>(from url: URL) async throws -> T {
        do {
            let (data, response) = try await URLSession.shared.data(from: url)
            
            guard let httpResponse = response as? HTTPURLResponse else {
                throw NetworkError.invalidResponse
            }
            
            guard (200...299).contains(httpResponse.statusCode) else {
                throw NetworkError.serverError(httpResponse.statusCode)
            }
            
            return try JSONDecoder().decode(T.self, from: data)
        } catch is DecodingError {
            throw NetworkError.decodingFailed
        } catch {
            throw error
        }
    }
}

Now, your networking layer is type-safe, generic, and provides meaningful errors. You've moved from "something went wrong" to "the server returned a 404," which makes debugging your frontend a whole lot easier.




📋 Practical Task

Exercise: Building a Type-Safe GitHub API Client

Your task is to implement a small networking client that can fetch two different types of data from the GitHub API: Users and Repositories.

Requirements:

  • Create a GitHubUser struct and a GitHubRepo struct, both conforming to Codable. Each should have at least two properties (e.g., login and id for users; name and stargazers_count for repos).
  • Implement a GitHubClient class with a generic method fetch<T: Decodable>(endpoint: String) async throws -> T.
  • Inside the method, construct the full URL using the base https://api.github.com and the provided endpoint string.
  • Use URLSession.shared.data(from:) to fetch the data and JSONDecoder to decode it into type T.
  • In a Task block or a main function, use the same GitHubClient instance to fetch a user (endpoint: "/users/apple") and a repository (endpoint: "/repos/apple/swift"), printing the results to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.