Browse Questions
- Store tokens securely in the Keychain, attach them to requests via a header, and refresh automatically when a 401 is received.
- Delegation is a pattern where one object hands off responsibility to another through a protocol, letting a child communicate back to its owner without knowing its concrete type.
- Use @Binding to pass a two-way connection into the sheet, so changes inside the sheet reflect in the parent.
- - Inheritance — a class derives behaviour from a parent class ("is-a" relationship) - Composition — a type gets behaviour by holding references to other objects ("has-a" relationship) Swift…
Answer:
Delegation is a pattern where one object hands off responsibility to another through a protocol, letting a child communicate back to its owner without knowing its concrete type. UIKit uses it everywhere — UITableViewDelegate, UITextFieldDelegate, UIScrollViewDelegate — and the delegate property is always weak to break the retain cycle that would otherwise form between parent and child.
Code Example:
// 1. Delegation — best for multiple related callbacks
protocol PaymentViewDelegate: AnyObject { // AnyObject required for weak
func paymentViewDidTapPay(_ view: PaymentView, amount: Decimal)
func paymentViewDidCancel(_ view: PaymentView)
}
final class PaymentView: UIView {
weak var delegate: PaymentViewDelegate? // weak — parent owns us, we don't own parent
@objc private func payTapped() {
delegate?.paymentViewDidTapPay(self, amount: total)
}
}
// 2. Closure — best for a single callback, keeps call site local
final class TipView: UIView {
var onPay: ((Decimal) -> Void)?
}
tipView.onPay = { [weak self] amount in // [weak self] — view retains the closure
self?.processPayment(amount)
}
// 3. Target-action — the Objective-C control mechanism
payButton.addTarget(self, action: #selector(payTapped), for: .touchUpInside)
// iOS 14+ modern equivalent, closure-based:
payButton.addAction(UIAction { [weak self] _ in self?.processPayment() }, for: .touchUpInside)
Key Points:
- Use delegation when there are several callbacks, or one needs a return value (
tableView(_:numberOfRowsInSection:)) - Use closures for one-off callbacks — less boilerplate, but always capture
selfweakly - Use target-action only for
UIControlsubclasses; preferUIActionon iOS 14+ weak var delegate+protocol X: AnyObjectis the rule — forgettingweakleaks the view controller