InterviewSolution
| 1. |
Explain the function of the completion handler. |
|
Answer» COMPLETION handlers are basically just functions passed as parameters to other functions. They are used to dealing with the response of asynchronous tasks since we do not know when they will end. Completion handlers inform an application when an operation, such as an API call, has been completed. The program is INFORMED that the next STEP needs to be executed. Example: Let's create a simple class called CompletionHandler that has one method called count that COUNTS from 0 to 50. Once it reaches 25 (a random value), it will make a network request to https://scaler.com. Once the request has been completed, we will print Received response. class CompletionHandler { func count() { for i in 0...50 { if i == 25 { if let url = URL(string: "https://scaler.com") { URLSession.shared.dataTask(with: url) { (data, response, error) in print("Received response") }.resume() } } print("I = ", i) } }}let newInstance = CompletionHandler()newInstance.count()You will see all the numbers printed out in the console as SOON as the code runs, but the Received response will be printed only after all those other numbers have been printed. |
|