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
115: Recovering from Errors Gracefully
I see this all the time: a developer writes a do-catch block, throws a print(error) inside the catch, and thinks they've "handled" the error. On the developer's machine, it looks fine because the error pops up in the Xcode console. But for the user? The app just stops responding, a loading spinner spins forever, or a button simply does nothing when clicked.
struct ProfileManager {
func loadUserProfile() async {
do {
let profile = try await NetworkService.shared.fetchProfile()
self.userProfile = profile
} catch {
// The classic mistake: logging is not handling.
print("Error loading profile: \(error)")
}
}
}
The "Silent Fail" Trap
The code above is technically "safe" in that it won't crash the app, but it's a failure in user experience. If the network is down or the server returns a 404, the catch block executes, prints a message that the user will never see, and the function exits. The app is now in a "zombie state"—the UI thinks it's still loading, but the logic has already given up.
Recovering gracefully means moving from detecting an error to responding to it in a way that keeps the user in control. You need to bridge the gap between the Swift error and the UI state.
Mapping Errors to User Actions
To fix this, we need to stop treating all errors as the same. A "no internet" error requires a different recovery path than a "password expired" error. I prefer using pattern matching in the catch block to determine exactly how the app should recover.
enum ProfileError: Error {
case noInternet
case serverDown
case userNotFound
}
struct ProfileManager {
var errorMessage: String?
var shouldShowRetryButton = false
func loadUserProfile() async {
do {
self.userProfile = try await NetworkService.shared.fetchProfile()
self.errorMessage = nil
self.shouldShowRetryButton = false
} catch ProfileError.noInternet {
self.errorMessage = "You're offline. Please check your connection."
self.shouldShowRetryButton = true
} catch ProfileError.serverDown {
self.errorMessage = "Our servers are taking a nap. Try again in a few minutes."
self.shouldShowRetryButton = true
} catch {
self.errorMessage = "Something went wrong. We're not quite sure what."
self.shouldShowRetryButton = false
}
}
}
Now, the app actually recovers. Instead of a frozen screen, the user gets a clear explanation and a way to fix the problem. I've also added a generic catch at the end—always do this. You can't predict every possible error (like a system-level memory issue), so you need a safety net to ensure the UI doesn't just hang.
Strategic Retries and Fallbacks
Sometimes, the most graceful recovery is one the user doesn't even notice. If you're loading a profile picture and it fails, does the whole screen need to show an error? Probably not. A better approach is a fallback.
I often implement a "silent retry" for transient errors. If the first attempt fails due to a timeout, try once more before bothering the user. If that also fails, fall back to a cached version of the data or a placeholder image. This creates a seamless experience where the app feels resilient rather than fragile.
📋 Practical Task
Building a Robust File Importer with Retry Logic
You are building a feature that imports a JSON configuration file from a local directory. Currently, the code just fails and prints to the console if the file is missing or corrupted.
Your Task: Refactor the FileImporter class to implement graceful recovery. You must:
- Define a
FileErrorenum with cases forfileNotFoundandcorruptedData. - Modify the
importConfig()method to usedo-catchwith specific pattern matching. - If
fileNotFoundoccurs, the app should call a methodcreateDefaultConfig()to generate a fresh file and then attempt to import it again. - If
corruptedDataoccurs, the app should set auserAlertMessagevariable informing the user that the file is broken and they must manually delete it. - Ensure there is a final catch-all block to handle unexpected system errors.
// Starting point
class FileImporter {
var userAlertMessage: String?
func importConfig() {
do {
try performImport()
} catch {
print("Import failed: \(error)")
}
}
func performImport() throws {
// Imagine this throws FileError.fileNotFound or .corruptedData
}
func createDefaultConfig() {
print("Creating a fresh default config file...")
}
}There are no comments for now.