-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
129: Practice Exercise: Building a Type-Safe Networking Layer with async/await
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
GitHubUserstruct and aGitHubRepostruct, both conforming toCodable. Each should have at least two properties (e.g.,loginandidfor users;nameandstargazers_countfor repos). - Implement a
GitHubClientclass with a generic methodfetch<T: Decodable>(endpoint: String) async throws -> T. - Inside the method, construct the full URL using the base
https://api.github.comand the provided endpoint string. - Use
URLSession.shared.data(from:)to fetch the data andJSONDecoderto decode it into typeT. - In a
Taskblock or amainfunction, use the sameGitHubClientinstance to fetch a user (endpoint:"/users/apple") and a repository (endpoint:"/repos/apple/swift"), printing the results to the console.
There are no comments for now.