How do you use Swift’s Result type for error handling?
Instruction: Provide an example of using the Result type to handle success and failure cases in a network request.
Updated
Official answer
Result carries either a success value or an error. It is useful when a callback must report an operation's final outcome; async throws is another good interface when callers use Swift concurrency.
This complete callback API validates the URL, separates transport/HTTP/decoding failures and handles a missing-data result explicitly. It returns the task for cancellation:
import Foundation
struct User: Decodable, Sendable { let name: String }
enum NetworkError: Error {
case invalidURL, invalidResponse, missingData
case transport(any Error)
case httpStatus(Int)
case decoding(any Error)
}
func decodeResponse(
data: Data?, response: URLResponse?, error: (any Error)?
) -> Result<User, NetworkError> {
if let error { return .failure(.transport(error)) }
guard let http = response as? HTTPURLResponse else {
return .failure(.invalidResponse)
}
guard (200..<300).contains(http.statusCode) else {
return .failure(.httpStatus(http.statusCode))
}
guard let data else { return .failure(.missingData) }
do { return .success(try JSONDecoder().decode(User.self, from: data)) }
catch { return .failure(.decoding(error)) }
}
@discardableResult
func fetchUser(
from text: String, session: URLSession = .shared,
completion: @escaping @Sendable (Result<User, NetworkError>) -> Void
) -> URLSessionDataTask? {
guard let url = URL(string: text),
url.scheme?.lowercased() == "https", url.host != nil else {
completion(.failure(.invalidURL))
return nil
}
let task = session.dataTask(with: url) { data, response, error in
completion(decodeResponse(data: data, response: response, error: error))
}
task.resume()
return task
}
func message(for result: Result<User, NetworkError>) -> String {
switch result {
case .success(let user): return "Hello, \(user.name)"
case .failure: return "The user could not be loaded."
}
}
Invalid input invokes completion synchronously on the caller's context; network completion runs on the session's delegate queue. This contract does not promise MainActor delivery. UI callers must explicitly hop to the main actor, handle stale requests and cancellation, and avoid retaining an obsolete screen through the callback. A cancellation is reported through the transport-error path.
The generic user-facing message avoids leaking server details, while the typed error preserves information for appropriate diagnosis. Test every branch, including a non-HTTP response, valid JSON with a failing HTTP status and missing data. Result itself does not make a callback run exactly once, enforce authentication or guarantee delivery after process termination.