Swift
Completed
-
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
84: async/await with URLSession
For a long time, the standard way to grab data from the web in Swift was using dataTask(with:completionHandler:). If you've spent any time in older codebases, you've seen it everywhere. It works, but it forces you into a mental model of "I'll tell you when I'm done" rather than "give me the result." When you start chaining multiple network requests—say, fetching a user's profile and then using that profile ID to fetch their recent posts—you end up in what we call "callback hell," where your code drifts further and further to the right of the screen.
The Callback Labyrinth
Let's look at a naive implementation of a user profile fetcher. Imagine we're hitting an API to get a User object. In the old way, the logic is fragmented. You have to handle the error, the response, and the data as three separate optional values, which is honestly a bit of a design mess.
func fetchUser(id: Int, completion: @escaping (Result<User, Error>) -> Void) {
let url = URL(string: "https://api.example.com/users/\(id)")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(URLError(.badServerResponse)))
return
}
do {
let user = try JSONDecoder().decode(User.self, from: data)
completion(.success(user))
} catch {
completion(.failure(error))
}
}.resume()
}
I've written this pattern a thousand times, and the biggest risk isn't the complexity—it's the human error. It is incredibly easy to forget to call completion() in one of those guard blocks. If you do that, the calling code just hangs forever, waiting for a response that will never come. There's no compiler warning for this; your app just stops reacting, and you're left staring at a loading spinner until you find the missing line of code.
Flattening the Logic with async/await
With async/await, we stop treating the network request as a "task to be started" and start treating it as a "value to be awaited." URLSession now provides a much cleaner method: data(from:delegate:). This doesn't take a completion handler; it simply returns a tuple containing the data and the response, or it throws an error.
func fetchUser(id: Int) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
// The execution pauses here until the request finishes
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}
Notice how the "pyramid of doom" has completely vanished. The code reads top-to-bottom, exactly how it executes. I love this because the error handling is now centralized. If the network fails, URLSession throws. If the JSON is malformed, JSONDecoder throws. Instead of five different if let or guard statements, you just wrap the call to fetchUser in a single do-catch block at the call site.
The Cost of the Switch
Now, you might wonder if this is just syntactic sugar. It's more than that. The old dataTask approach relies on closures that capture self, which often leads to memory leaks (strong reference cycles) if you aren't careful with [weak self]. With async/await, the Swift runtime manages the suspension point. The function "pauses," frees up the thread for other work, and resumes when the data arrives.
The only real "cost" is that you have to be mindful of the context. You can't call an async function from a synchronous one without creating a Task. But in a modern SwiftUI or UIKit app, this is almost always the trade-off you want. You're trading a tiny bit of setup overhead for a massive gain in maintainability and a total elimination of the "forgotten completion handler" bug.
📋 Practical Task
Exercise: Build an Async GitHub User Lookup
Your goal is to create a service that fetches a user's public profile from the GitHub API. You will move away from completion handlers and implement a fully asynchronous flow.
Requirements:
- Define a
GitHubUserstruct that conforms toCodable, containing at least thelogin(username) andpublic_repos(number of repositories) fields. - Write an
asyncfunction calledfetchGitHubProfile(for username: String)that:- Constructs a URL using
"https://api.github.com/users/\(username)". - Uses
URLSession.shared.data(from:)to fetch the data. - Decodes the resulting data into a
GitHubUserobject. - Throws an error if the network request fails or the decoding fails.
- Constructs a URL using
- Create a
Taskblock to call this function for a real GitHub username (e.g., "apple") and print the number of public repositories to the console. Wrap this call in ado-catchblock to handle potential errors gracefully.
There are no comments for now.