3

I don't clear about these two, Nowadays the world is shifting to the closure types. But I'm not clearly understanding this. Can someone explain me with a real-time example?

Surezz
  • 561
  • 4
  • 12

3 Answers3

5

So a real life example of both would be something like this:

protocol TestDelegateClassDelegate: class {
    func iAmDone()
}

class TestDelegateClass {
    weak var delegate: TestDelegateClassDelegate?

    func doStuff() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.delegate?.iAmDone()
        }
    }
}

class TestClosureClass {
    var completion: (() -> Void)?

    func doStuff() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.completion?()
        }
    }
}


class ViewController: UIViewController, TestDelegateClassDelegate {

    func iAmDone() {
        print("TestDelegateClassDelegate is done")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let testingDelegate = TestDelegateClass()
        testingDelegate.delegate = self
        testingDelegate.doStuff()

        let testingClosure = TestClosureClass()
        testingClosure.completion = {
            print("TestClosureClass is done")
        }
        testingClosure.doStuff()

    }

}

Here we have 2 classes TestDelegateClass and TestClosureClass. Each of them have a method doStuff which waits for 3 seconds and then reports back to whoever is listening where one uses delegate procedure and the other one uses closure procedure.

Although they do nothing but wait you can easily imagine that they for instance upload an image to server and notify when they are done. So for instance you might want to have an activity indicator running while uploading is in progress and stop it when done. It would look like so:

class ViewController: UIViewController, TestDelegateClassDelegate {

    @IBOutlet private var activityIndicator: UIActivityIndicatorView?

    func iAmDone() {
        print("TestDelegateClassDelegate is done")
        activityIndicator?.stopAnimating()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        activityIndicator?.startAnimating()
        let testingDelegate = TestDelegateClass()
        testingDelegate.delegate = self
        testingDelegate.doStuff()

        activityIndicator?.startAnimating()
        let testingClosure = TestClosureClass()
        testingClosure.completion = {
            self.activityIndicator?.stopAnimating()
            print("TestClosureClass is done")
        }
        testingClosure.doStuff()

    }

}

Naturally you would only use one of the two procedures.

You can see there is a huge difference in code. To do a delegate procedure you need to create a protocol, in this case TestDelegateClassDelegate. A protocol is what defines the interface of a listener. And since an iAmDone method is defined it must be defined in ViewController as well as long as it is defined as TestDelegateClassDelegate. Otherwise it will not compile. So anything declared as TestDelegateClassDelegate will have that method and any class can call it. In our case we have weak var delegate: TestDelegateClassDelegate?. That is why we can call delegate?.iAmDone() without caring what delegate actually is. For instance we can create another class:

class SomeClass: TestDelegateClassDelegate {
    func iAmDone() {
        print("Something cool happened")
    }
    init() {
        let testingDelegate = TestDelegateClass()
        testingDelegate.delegate = self
        testingDelegate.doStuff()
    }
}

So a good example for instance is an UITableView that uses a delegate and dataSource (both are delegates, just properties are named differently). And table view will call the methods of whatever class you set to those properties without needing to know what that class is as long as it corresponds to the given protocols.

Same could be achieved with closures. A table view could have been defined using properties giving closures like:

tableView.onNumberOfRows { section in
    return 4
}

But that would most likely lead into one big mess of a code. Also closures would in this case be giving many programmers headaches due to potential memory leaks. It is not that closures are less safe or anything, they just do a lot of code you can't see which may produce retain cycles. In this specific case a most likely leak would be:

tableView.onNumberOfRows { section in
    return self.dataModel.count
}

and a fix to it is simply doing

tableView.onNumberOfRows { [weak self] section in
    return self?.dataModel.count ?? 0
}

which now looks overcomplicated.

I will not go into depths of closures but in the end when you have repeated call to callbacks (like in case of table view) you will need a weak link either at delegate or in closure. But when the closure is called only once (like uploading an image) there is no need for a weak link in closures (in most but not all cases).

In retrospective use closures as much as possible but avoid or use caution as soon as a closure is used as a property (which is ironically the example I gave). But you would rather do just this:

func doSomethingWithClosure(_ completion: @escaping (() -> Void)) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
        completion()
    }
}

And use it as

    doSomethingWithClosure {
        self.activityIndicator?.stopAnimating()
        print("TestClosureClass is done")
    }

This has now removed all potential risks. I hope this clears a thing or two for you.

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43
2

In Swift/obj-c the term delegate is used to refer to a protocol that responds to specific selectors.

Thing about it just like calling a method on an object.

E.g.

protocol CalculatorDelegate : class { // : class so it can be made 'weak'
 func onCalculation(result: Int) -> Void
}

Now if we have a Calculator class, to use the delegate we'd do something like

class Calculator() {
  weak var delegate: CalculatorDelegate?

  func calculate(_ a: Int, _ b: Int) -> Int {
    let result = a + b

    self.delegate?.onCalculation(result: result)
    return result
  }
}

Then in some other class (e.g. in iOS - a View Controller) we might do:

class MyClass : CalculatorDelegate {
 func onCalculation(result: Int) {
   print("Delegate method on calculation called with result \(result)")
 }

 func someButtonPress() {
  let calculator = Calculator()
  calculator.delegate = self
  calculator.calculate(42, 66)
 }
}

So you can see how the setup is quite elaborate.

Now closures are simply blocks of code that can be called in other places, so you could change all of the code like so:

class Calculator2() {
  weak var delegate: CalculatorDelegate?

  func calculate(_ a: Int, _ b: Int, onCalculation: (@escaping (Int) -> Void) -> Int)?) {
    let result = a + b

    onCalculation?(result)
    return result
  }
}
class MyClass {
 func someButtonPress() {
  let calculator = Calculator2()
  calculator.calculate(42, 66, onCalculation: { (result: Int) in 
    print("Closure invoked with \(result)")
  })
 }
}

However, with closures you need to be aware that it is a lot easier to shoot yourself in the foot by capturing variables (e.g. self) strongly, which will lead to memory leaks even under ARC regime.

zaitsman
  • 8,984
  • 6
  • 47
  • 79
1

Closures are first-class objects so that they can be nested and passed around Simply, In swift, functions are primitive data types like int, double or character that is why you can pass a function in the function parameter. In swift mechanism simplify in closures syntax like lambda expression in other languages.

E.g. If you want to call rest API through URSSession or Alamofire and return response data then you should use completionHandler(it's closure).

Void closure : - {(paramter:DataType)->Void}

Return closure : - {(paramter:DataType)->DataType} e.g. (int, int) -> (int) https://docs.swift.org/swift-book/LanguageGuide/Closures.html

Khadija Daruwala
  • 1,185
  • 3
  • 25
  • 54