What is Completion Handler ? How To Use ?

By admin
In SWIFT
Şubat 22, 2023
2 min read

In Swift, there is a construct called a “completion handler” for functions that are called when an operation is completed. Completion handler is a block that is called when a transaction is complete and is usually used to handle the results or errors of an asynchronous operation.

Completion handler has several different use cases. One of them is a completion handler, which is used when downloading data from a data source. When the download is complete, the completion handler processes the results or errors.

For example:

func fetchData(completionHandler: @escaping (Result<Data, Error>) -> Void) {
// Data download process from data source
// The completion handler is called when the process is complete
if let downloadedData = downloadedData {
completionHandler(.success(downloadedData))
} else {
completionHandler(.failure(DataError.downloadFailed))
}
}

In the example above, the “fetchData” function accepts a completion handler and is called with a “Result” object that contains a “Data” element on success or an “Error” element on failure.

Its use is also quite common for a function to report the transaction completion status.

For example:

func performLongRunningTask(completion: @escaping (Bool) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
// Do a long running task here
let result = true // Mission successfully completed
completion(result) // The completion handler is called when the task is complete
}
}

In the example above, the “performLongRunningTask” function starts a long-running task, and a completion handler is called when the process is complete. This completion handler accepts a “Bool” value indicating successful completion of the task.

Completion handler use is very common for asynchronous programming and can increase code readability and maintainability.

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir