DEV Community

mrcflorian
mrcflorian

Posted on

iOS Design Patterns: The Facade Pattern in Swift

In the past two years, we’ve built more than 20 fully functional iOS Templates. As you can image, code reusability is one of the top priorities for us, when it comes to creating an iOS app. In this article, we are taking a look at the Facade Pattern. Let’s understand what it is and what architectural approach it takes.

adapter pattern

The facade pattern (also spelled façade) is a software-design pattern commonly used in object-oriented programming. Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex underlying or structural code. You can read up the official generic Facade definition on Wikipedia.

If you ever created a simple APIClient / APIManager class, you’ve used the Facade Design Pattern. Creating a simple APIClient/APIManager object that’s encapsulating the networking, is indeed a facade to the Alamofire or URLSession functionality.

Facade Example

If you’ve ever worked with the KeyChain, you know that Apple’s APIs are extremely cumbersome. In fact, almost no one used those APIs. Most of the iOS developers we know usually use a third party open source Swift project that wraps the logic of the KeyChain, hiding all those hideous interfaces. These Swift libraries are facades themselves.

For a simple facade example, let’s build a simple facade object for the storing values in Keychain

class KeychainFacade {

    func save(value: String, forKey key: String) throws {
        // save to Keychain logic
    }

    func readValue(forKey key: String) -> throws String {
        // read value from Keychain logic
    }
}
Enter fullscreen mode Exit fullscreen mode

Summary

The facade design pattern is widely spread in the industry, and chances are you’ve already used it, without realizing it. It is not something specific to Swift, but a generic design pattern, widely spread in the industry. In fact, it can be used even in Javascript or React Native apps. It is used to hide implementation details and abstract out interfaces so that consumers can deal with a lower level of details. While it adds an extra layer of abstraction, the facade design pattern improves the readability and architecture of the code significantly.

Top comments (0)