What are delegates in iOS?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Swift & iOS development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
The Delegate pattern is a core iOS design pattern where one object (the delegating object) communicates back to another object (the delegate) through a protocol. Used extensively in UIKit: UITableViewDelegate, UITextFieldDelegate, URLSessionDelegate, etc. Implementation example: // Step 1: Define protocol protocol TaskDelegate: AnyObject { func taskDidStart(_ task: Task) func taskDidComplete(_ task: Task, result: String) func taskDidFail(_ task: Task, error: Error) } // Step 2: Delegating class holds a weak reference class Task { weak var delegate: TaskDelegate? // WEAK to avoid retain cycle var name: String init(name: String) { self.name = name } func start() { delegate?.taskDidStart(self) // Perform work... delegate?.taskDidComplete(self, result: "Done") } } // Step 3: Delegate implements protocol class ViewController: UIViewController, TaskDelegate { let task = Task(name: "Download") override func viewDidLoad() { super.viewDidLoad() task.delegate = self task.start() } func taskDidStart(_ task: Task) { print("Task started: \(task.name)") } func taskDidComplete(_ task: Task, result: String) { print("Task done: \(result)") } func taskDidFail(_ task: Task, error: Error) { print("Task failed: \(error)") } }. Why weak delegate? Prevents retain cycle — delegating object holding the delegate strongly + delegate holding delegating object strongly = leak. UITableView delegation: tableView.dataSource = self tableView.delegate = self. Override protocol methods to provide cell count, cells, heights, selection handling.
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Swift & iOS answers easy to follow.
Previous
What is the difference between @ObservedObject, @StateObject, and @EnvironmentObject?
Next
What is UITableView and how do you implement it?