Designing patterns used during iOS app development


In this tutorial, you will get to know about some common design patterns that you should follow while making iOS apps.

What are Swift Design Patterns?

In Swift, design patterns make the development process easy for developers. A productive and effective work environment can be created by following the design patterns. An iOS design pattern is a set of repeatable methods for creating apps.

What are the most common design patterns used in iOS development?

  • Builder

  • Facade

  • MVC

  • Singleton

  • Viper

  • MVVM

  • Adaptor

  • Observer

  • Factory Method

Let's talk about some of them to understand how they work −

Algorithm

Step 1 − Create an enum for food categories.

Step 2 − Create basic models for storing food items and ordering items.

Step 3 − Create a model for storing order details and calculating the order price.

Step 4 − Create a builder model to create and maintain orders.

Builder

The builder pattern is also known as the creational pattern that allows us to create objects in the Swift language. Using it, we can create complex objects by following the steps. A major benefit of using the builder pattern is that you can use the same piece of code for creating multiple object views.

Example

import Foundation
enum FoodCategory: Int {
   case firstCourses, mainCourses, drinks
}
struct FoodItem {
   var name: String
   var price: Float
}
struct OrderItem {
   var food: FoodItem
   var count: Int
}
struct OrderDetail {
   var firstCourses: [OrderItem] = []
   var mainCourses: [OrderItem] = []
   var drinks: [OrderItem] = []
   // calculating total price of the order
   var price: Float {
      let items = firstCourses + mainCourses + drinks
      return items.reduce(Float(0), { $0 + $1.food.price * Float($1.count) })
   }
}
// Builder Pattern
class OrderBuilder {
   private var order: OrderDetail?
   func reset() {
      order = OrderDetail()
   }
   func setFirstCourse(_ food: FoodItem) {
      set(food, at: order?.firstCourses, withCategory: .firstCourses)
   }
   func setMainCourse(_ food: FoodItem) {
      set(food, at: order?.mainCourses, withCategory: .mainCourses)
   }
   func setDrink(_ food: FoodItem) {
      set(food, at: order?.drinks, withCategory: .drinks)
   }
   func getResult() -> OrderDetail? {
      return order ?? nil
   }
   private func set(_ food: FoodItem,
      at orderCategory: [OrderItem]?,
   withCategory foodCategory: FoodCategory) {
      guard let orderCategory = orderCategory else {
         return
      }
      var item: OrderItem! = orderCategory.filter( { $0.food.name == food.name } ).first
      guard item == nil else {
         item.count += 1
         return
      }
      item = OrderItem(food: food, count: 1)
      switch foodCategory {
         case .firstCourses:
            order?.firstCourses.append(item)
         case .mainCourses:
            order?.mainCourses.append(item)
         case .drinks:
            order?.drinks.append(item)
      }
   }
}
// Usage
let butterKulcha = FoodItem(name: "Butter Kulcha", price: 60)
let lassi = FoodItem(name: "Mango Lassi", price: 90)
let builder = OrderBuilder()
builder.reset()
builder.setMainCourse(butterKulcha)
builder.setDrink(lassi)
let order = builder.getResult()
print("Order Price: \(order?.price ?? 0.0)")

Output

Order Price: 150.0

Facade

To store information, you usually work with classes. In that case, you can create your own class and wrap other class objects in it. Using the facade pattern, you can separate system logic into different layers. It helps you to manage project code easily with multiple layers.

Using Facade as an example can help you integrate audio recording and playback into your iOS app. Using Facade, you can hide the file system.

MVC

MVC is also known as Model View Controller. This is one of the most popular design pattern in iOS development. Apple also makes all their demo applications using this design pattern which we can see in Apple documentation. Using the MVC pattern, you can create separate layers like Model for business logic, View for user interface, and Controller for controlling the user flow.

The 3 Functions of the Mechanism are

  • A model is used to store business logic and data, and to manipulate the data. Generally, we use classes or structs for storing the information.

  • A view is used to design the user interface on which a user can interact. Basically, Swift provides many different view components for different uses.

  • A controller is used to control the data flow between the model and the view. It plays an important role in this design pattern.

When should you use MVC Patterns for iOS Apps?

  • You should use it to main the code for data flow and messaging.

  • To write the code into a proper structure.

  • To make the development process fast.

  • To write simple and clean code.

  • To write code that is easily understood by other developers.

Singleton

When you are required to deal with a single instance all the time, the Singleton design pattern will help you. Using it, you can create a single instance throughout the app life cycle.

Practically, you should avoid using the Singleton pattern as it might be possible to face some issues with it. But sometimes, you need to work with a single object to share the same instance with multiple components.

When should you use the Singleton pattern in Swift?

  • When a class in your program should have just a single instance for all clients

  • When you need strict control over global variables.

MVVM (Model-View-ViewModel)

This is the favorite design pattern among iOS developers. MVVM is also known as Model View View Model. This design pattern includes all the components like Views, Models, Controllers, Animations, Multi-thread, Databases, etc.

In addition, the ViewModel layer between the View and the Model represents the view in a canonical manner. The ViewModel thus provides a set of interfaces, and each interface represents UI components.

Observer

In Swift, using different and multiple objects we can define the one-to-one and one-to-many relationships between objects. For example, you want to observe the changes made in an object, and based on that you can perform actions. In the same case, an observer design pattern is very helpful to observe the changes and perform further actions.

In an observer design pattern, subjects and observers are loosely coupled.

Adaptor

To develop the iOS design pattern app, the adapter design pattern converts the class interface into another interface based on client requirements.

Using this adaptor, classes can interact with one another while separating the client from the object's class.

Conclusion

In this article, we talked about the different and most commonly used design patterns in iOS development. They can be used in different situations and requirements. While developing an iOS application, it is most important to follow the design patterns properly to write clean and safe code.

Basically, for developing a small application you can use an MVC design pattern. But for large applications, MVVM is the recommended design pattern to use.

Updated on: 21-Dec-2022

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements