Concurrency in Swift: Continuations
4 min readNov 19, 2022
Continuations in Swift are for converting synchronous code into asynchronous code. We can now convert closures into async await functions that allow for structured concurrency. In this article I’m going to show you how to use continuations and talk about the different types you can do. There are two types of continuations: CheckedContinuation and UnsafeContinuation.
Let’s start off by how we used to write network calls. Below is a function called “getAllBreeds” with an escaping closure that takes a Result type.
func getAllBreeds(completion: @escaping (Result<[Breed], Error>) -> Void) {
let url = URL(string: Self.endpoint.appending("breeds/list/all"))!
let urlRequest = URLRequest(url: url)
URLSession.shared.dataTask(with: urlRequest) { data, response, error in
if let err = error {
completion(.failure(ServiceError.sessionError(err)))
}
guard let data = data else {
completion(.failure(ServiceError.badData))
return
}
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
completion(.failure(ServiceError.badHTTPResponse))
return
}
let decoder = JSONDecoder()
do {
let resource = try decoder.decode(BreedResource.self, from: data)
completion(.success(resource.breeds))
} catch let error as DecodingError {…