Middle
What completion handler did you write?
sobes.tech AI
Answer from AI
I have written many completion handlers for various tasks, including:
- Handling network request results (receiving data, execution status).
- Asynchronous database operations (saving, reading, updating).
- Filesystem operations (reading, writing, deleting).
- Animations and user interfaces (completing animations, handling user gestures).
- Custom asynchronous operations with the ability to pass results and errors.
For example, when working with URLSession, I often use this pattern:
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
// Error handling
completion(.failure(error))
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode),
let data = data else {
// Handling invalid response or data
completion(.failure(URLError(.badServerResponse)))
return
}
// Successful data processing
do {
let model = try JSONDecoder().decode(SomeModel.self, from: data)
completion(.success(model))
} catch {
// Error handling for decoding
completion(.failure(error))
}
}.resume()
where completion is a closure of type (Result<SomeModel, Error>) -> Void. Using Result allows clear separation of success and failure.