UIKit delegates and protocols

3479
0

Delegates enable objects to communicate events and customize behavior. The delegate pattern uses protocols to define a contract—I create a protocol with optional and required methods, and the delegating object holds a weak reference to avoid retain cycles. Common system delegates include UITableViewDelegate, UITextFieldDelegate, and UICollectionViewDelegate. For custom delegates, I define protocols for specific responsibilities like network callbacks or view controller events. The weak keyword prevents retain cycles when parent objects delegate to children. Protocols can have associated types with associatedtype for generic constraints. This pattern promotes loose coupling and testability through dependency injection.