Vijay Kahar
Vijay Kahar

Reputation: 1076

CompletionHandler and Closure

I have some questions here,

1) What is CompletionHandler and Closure and when to use it? 2) Closure vs CompletionHandler

it's a bit confusing for me.

Upvotes: 0

Views: 2249

Answers (1)

alexisSchreier
alexisSchreier

Reputation: 677

Completion handler and closure are synonyms. They are called blocks in Objective-C.

You can think of them as objects that execute a bloc of code when they are called (much like a function).

// My view controller has a property that is a closure
// It also has an instance method that calls the closure
class ViewController {

    // The closure takes a String as a parameter and returns nothing (Void)
    var myClosure: ((String) -> (Void))?
    let helloString = "hello"

    // When this method is triggered, it will call my closure
    func doStuff() {
        myClosure(helloString)?
    }
}

let vc = ViewController()

// Here we define what the closure will do when it gets called
// All it does is print the parameter we've given it
vc.myClosure = { helloString in
    print(helloString) // This will print "hello"
}

// We're calling the doStuff() instance method of our view controller
// This will trigger the print statement that we defined above
vc.doStuff()

A completion handler is just a closure that is used to complete a certain action: once you have finished doing something, you call your completion handler which executes code to complete that action.

This is just a basic explanation, for more detail you should check out the docs: https://docs.swift.org/swift-book/LanguageGuide/Closures.html

Upvotes: 3

Related Questions