Sobes.tech
Junior — Middle

What is the role of delegates in your code and what are they used for?

sobes.tech AI

Answer from AI

Delegates in iOS are a design pattern that allows one object to pass responsibility for executing certain actions to another object. This is a way to organize feedback and communication between objects without tight coupling.

Role of delegates:

  • Allow an object to notify another object about events.
  • Provide customization of behavior without inheritance.
  • Simplify separation of responsibilities.

Example: UITableView uses a delegate to handle cell selection. A class implementing the UITableViewDelegate protocol receives notifications about user actions.

protocol MyDelegate: AnyObject {
    func didTapButton()
}

class MyClass {
    weak var delegate: MyDelegate?

    func buttonTapped() {
        delegate?.didTapButton()
    }
}

class ViewController: UIViewController, MyDelegate {
    let myObject = MyClass()

    override func viewDidLoad() {
        super.viewDidLoad()
        myObject.delegate = self
    }

    func didTapButton() {
        print("Button tapped")
    }
}
What is the role of delegates in your code and what… - sobes.tech