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
114: Result Type In Depth
A few years ago, I was reviewing a PR from a junior dev who had built a network layer for a weather app. He was using the old-school pattern of returning a tuple in the completion handler: completion((WeatherData?, Error?)). During a stress test, we hit a weird edge case where the server returned a 200 OK but an empty body. The completion handler fired with (nil, nil). The UI just hung there, spinning forever, because the code was checking if let data = data and if let error = error. Since both were nil, neither block executed. It was a classic "impossible state" that actually became possible.
This is exactly why the Result type exists. It turns that ambiguous "maybe this, maybe that" into a strict "either this OR that."
Escaping the Ambiguity of Optional Tuples
When you use (T?, Error?), you're telling the compiler that there are four possible outcomes: success with data, failure with an error, both, or neither. In reality, your logic only cares about two. The Result type is an enum with two cases: .success(Success) and .failure(Failure). By using it, you make the "impossible states" unrepresentable in your code.
enum APIError: Error { case networkFailure case invalidResponse case decodingError } func fetchUserBio(userId: String, completion: @escaping (Result<String, APIError>) -> Void) { // Simulate a network call let success = true if success { completion(.success("Software Engineer and Swift enthusiast.")) } else { completion(.failure(.networkFailure)) } }Now, whoever calls
fetchUserBiois forced to handle the result using aswitchstatement. They can't forget the error case, and they can't accidentally handle a state where both data and error are missing. It's a much safer contract between the function and the caller.Handling Custom Error Types
One of the most powerful parts of
Result<Success, Failure>is that theFailuretype must conform to theErrorprotocol. While you could just useError(the existential type), I strongly recommend using a specific enum. This allows the caller to react differently depending on why the call failed.Think about it: you don't handle a "Wrong Password" error the same way you handle a "Server is Down" error. By defining a specific error enum for your Result, you give the UI layer the information it needs to show a helpful message instead of a generic "Something went wrong."
Transforming Results without Switching
You don't always want to
switchon a result immediately. Sometimes you just want to transform the successful value and pass it along. Swift providesmapandflatMapon theResulttype, which lets you stay in the "Result wrapper" while modifying the inner value.let result: Result<String, APIError> = .success("hello world") // Use map to transform the success value let upperCaseResult = result.map { $0.uppercased() } // upperCaseResult is now Result<String, APIError> containing .success("HELLO WORLD") // Use flatMap when the transformation itself could fail let trimmedResult = upperCaseResult.flatMap { text -> text.count > 0 ? .success(text) : .failure(.invalidResponse) }I find that using
mapandflatMapkeeps the code much cleaner. It allows you to chain several operations together and only "unwrap" the result at the very end when you're ready to update the UI or log the error.
📋 Practical Task
Refactoring the Legacy WeatherAPI Client
You've inherited a legacy piece of code that uses the dangerous (Data?, Error?) pattern. Your task is to refactor the WeatherService to use the Result type to ensure type safety and eliminate impossible states.
Requirements:
- Define a
WeatherErrorenum (conforming toError) with cases for.noDataand.serverError. - Change the
fetchWeatherfunction signature to useResult<WeatherData, WeatherError>. - Update the mock implementation to return
.successor.failure. - Implement a caller that uses a
switchstatement to print the weather temperature on success or a specific error message on failure.
// Start with this legacy structure:
struct WeatherData {
let temperature: Double
}
class WeatherService {
func fetchWeather(completion: @escaping (WeatherData?, Error?) -> Void) {
// Mocking a failure
completion(nil, NSError(domain: "Weather", code: 404))
}
}There are no comments for now.