Blibli.com Dec 18, 2020

Delegation Pattern in Swift

M6 Related OWASP risk: Inadequate Privacy Controls Learn more →

Article Summary

Williams Perdana from Blibli.com uses a CEO analogy to explain one of Swift's most powerful patterns. Just like a CEO delegates to department heads, your code can delegate responsibilities to keep things clean and maintainable.

This practical guide breaks down the delegation pattern in Swift using a real-world book list app example. Perdana walks through how protocols enable view controllers to communicate without tight coupling, making code more reusable and testable.

Key Takeaways

Critical Insight

The delegation pattern keeps Swift code loosely coupled by letting objects hand off responsibilities through protocol conformance instead of direct references.

The article reveals why adding previousController2, previousController3 variables would be a maintenance nightmare and how delegation elegantly solves it.

About This Article

Problem

Williams Perdana ran into a scalability issue. Reusing InputTitleVC across multiple view controllers meant creating separate variables for each controller type. Beyond 10+ view controllers, this approach became unmaintainable.

Solution

Perdana used Swift protocols to define a blueprint for saving methods. Any class that conformed to the protocol could provide its own implementation through delegation, without needing direct dependencies.

Impact

InputTitleVC could now be reused across FictionalBooksTableVC and EducationalBooksTableVC with different save implementations. This eliminated the need for multiple controller-specific variables and reduced code coupling.