Browse Questions
- Result<Success, Failure> is an enum with .success and .failure cases.
- NavigationStack (iOS 16+) replaces NavigationView and uses a path-based approach for programmatic navigation, making deep linking and state-driven navigation much cleaner.
- Define a clear error type, validate HTTP status codes, and propagate errors up to the UI where they can be shown to the user.
- MVVM (Model-View-ViewModel) separates business logic from UI.
Answer:
Result<Success, Failure> is an enum with .success and .failure cases. It makes error handling explicit and is ideal for async operations, replacing optional + error patterns.
Code Example:
enum NetworkError: Error {
case badURL
case noData
case decodingFailed
}
func fetchUser(id: Int, completion: @escaping (Result<User, NetworkError>) -> Void) {
guard let url = URL(string: "https://api.example.com/users/\(id)") else {
completion(.failure(.badURL))
return
}
// ... network call
completion(.success(user))
}
// Usage
fetchUser(id: 1) { result in
switch result {
case .success(let user):
print("Got user: \(user.name)")
case .failure(let error):
print("Error: \(error)")
}
}