Apple Design Patterns in iOS Swift

Suryakant Sharma
4 min readFeb 26, 2020

Here I will be discussing the design patterns that use in most of Apple’s frameworks.

Let’s dive in! 😀

What are design patterns?

Design patterns are a solution to recurring problems that a software developer faces. Using design patterns helps us with code decoupling, single responsibility and testability. It gives us a common vocabulary to use in the community which is independent of any language. This inspires me to learn and write evergreen design patterns.

Below are three types of design patterns

1. Creational patterns provide object creational mechanisms, which help us with increased flexibility and reusability of existing code.

2. Structural patterns explain how to assemble objects and classes into larger structures.

3. Behavioral design patterns are design patterns that identify common communication patterns between objects

Let us talk about the patterns used in the iOS SDKs

Singleton is a creational design pattern. It allows only one object to exist in the entire life cycle. To avoid misuse we should make init() private so no other instance can be created outside to avoid unnecessary bugs. Injecting the singletons make dependency more clear and easy for mock while testing.

let defaults = UserDefaults.standard
let application = UIApplication.shared
Singletons (credit: https://refactoring.guru/)

You can create simple singletons using a static type property. Which is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously.

If you need to perform additional setup beyond initialization. Then you can assign the result of the invocation of closure to the global constant.

You can read more on the apple doc here.

Chain of Responsibility ⛓️ is a behavioral design pattern. It allow you to pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or pass in chain.

e.g Each UIResponder in UI hierarchy decide either handle tap or pass on to other responders

chain of responsibility (credit https://refactoring.guru/)

Let us see how the responder chain works in the UI hierarchy when the user taps on the button of any iOS application.

UI hierarchy

Output:

Facade is the structural design pattern. It allows a single simplified interface for all external clients. A single class represents all subsystems.

e.g CoreData NSPersistentContainer. A container that encapsulates the Core Data stack in your app. NSPersistentContainer simplifies the creation and management of the Core Data stack by handling the creation of the managed object model (NSManagedObjectModel), persistent store coordinator (NSPersistentStoreCoordinator), and the managed object context (NSManagedObjectContext).

facade (credits: Facade-Raywenderlich)

Let’s see how we used to build the core data stack before iOS 10.

guard let modelURL = Bundle.main.url(forResource: "DataModel",
withExtension: "momd") else {
fatalError("Failed to find data model")
}
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Failed to create model from file: \(modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
let dirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
let fileURL = URL(string: "DataModel.sql", relativeTo: dirURL)
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType,
configurationName: nil,
at: fileURL, options: nil)
} catch {
fatalError("Error configuring persistent store: \(error)")
}

But after facade implementation, it is much easier now.

lazy var persistentContainer: NSPersistentContainer = {        
let container = NSPersistentContainer(name: "DataModel")
container.loadPersistentStores { description, error in
if let error = error {
fatalError("Unable to load persistent stores: \(error)")
}
}
return container
}()

Observer is a behavioral pattern that creates a one-to-many dependency between objects. When one object changes state, all its dependents are notified and can update.

e.g KVO, NotificationCenter.

Let see how we can implement our own observer pattern in swift.

Output:

Thanks for reading! 🚀

Resources:
https://sourcemaking.com/design_patterns

https://www.geeksforgeeks.org/software-design-patterns/

https://refactoring.guru/design-patterns

Thank you for reading! If you liked this article, please 👏 so other people can read it too :)

Follow me on Twitter for more.

📝 Save this story in Journal.

👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.

--

--