Swift Design Patterns: Facade Pattern

The Facade pattern can be used to make your code more modular, reusable, and easier to change

Photo by Clay Banks on Unsplash

Just like a store facade, it’s namesake programming pattern usually refers to an object that serves as a front-facing interface and masks more complex underlying or structural code.

In practice, the Facade pattern is a very important tool that can be used to make your code modular, reusable, and easy to change.

For instance, imagine that your app needs to present a Head-Up Display ( HUD ) every time the user clicks one of the three buttons in the following screen:

A sample screen where the app will display a HUD every time the user clicks one of the buttons.

To preset that HUD , you can implement the following piece of code in your SwiftUI view:

This is a very noob implementation of a HUD usage in a SwiftUI view, it contains a lot of code repetition!

As you can see, there are four lines of code repeated three times:

Chunk of code that initializes and calls the HUD library SVProgressHUD

We can surely do better than that! The most obvious thing to do here is to create a private method in our ContentView , called func showSuccessHUD(withStatus status: String, delay: TimeInterval = 2) :

A better implementation of a HUD usage in a SwiftUI view, removing a lot of code repetition inside the class.

This avoids a lot of code repetition inside the ContentView class but we haven't actually created a dedicated class to handle our HUD yet.

We could really benefit from having a specialized HUD service because we would not only avoid code repetition throughout the whole project, but it would also be much easier to replace our SVProgressHUD with another library or even with a custom implementation of our own.

This way, we can adapt our projects pretty easily whenever needed.

Let's have a look at what the HUD facade would look like:

Finally, the Facade pattern used for configuring and presenting a simple HUD

This could be used from anywhere in our code, by calling HUD.showSuccessHUD(withStatus: "Your message here") .

Why is this better? Your code becomes pretty adaptable because any changes in the HUD service would (likely) require a single file to be updated: the HUD.swift file.

In addition to that, this is the kind of code you can easily reuse across your projects to sharply improve your productivity and code quality!