The Observer Pattern in Swift

The Observer pattern is a design pattern that allows objects (observers) to register to receive notifications from another object (the subject). In Swift, the Observer pattern can be implemented using the ‘NotificationCenter‘ class and the ‘addObserver‘ method, like this:

class SomeObserver { 

  func startObserving() { 
    NotificationCenter.default.addObserver(
      self, 
      selector: #selector(handleNotification), 
      name: Notification.Name("silentMode"), 
      object: nil 
    ) 
  } 

  @objc func handleNotification(_ notification: Notification) { 
  // Handle the notification here. 
  } 
} 

class SomeSubject { 

  func sendNotification() { 
    NotificationCenter.default.post(
      name: Notification.Name("silentMode"), 
      object: self
    ) 
  } 
}

The SomeObserver class has a startObserving method that registers the handleNotification method as an observer of the silentMode notification. The handleNotification method will be called whenever the silentMode notification is posted by the SomeSubject class.

The SomeSubject class has a sendNotification method that posts the silentMode notification using the NotificationCenter class. This will trigger the handleNotification method on any objects that have registered as observers of the silentMode notification.

The Observer pattern is useful for allowing objects to communicate with each other without tightly coupling their behavior. It enables objects to react to changes in the state of the subject, and to receive notifications about important events without having to know the details of how the events are generated. By using the Observer pattern, developers can write more modular, flexible, and decoupled code.

Also read: The Singleton Pattern in Swift


Posted

in