Advanced and Practical Enum usage in Swift

Observer Pattern

released Fri, 01 Mar 2019
Swift Version 5.0

Observer Pattern

There're various ways of modelling observation in Swift. If you include @objc compatibility, you can use NotificationCenter or KVO. Even if not, the didSet syntax makes it easy to implement simple observation. Enums can be used here in order to make the type of change that happens to the observed object clearer. Imagine collection observation. If we think about it, we only have a couple of possible cases: One or more items are inserted, one or more items are deleted, one or more items are updated. This sounds like a job for an enum:

enum Change {

      case insertion(items: [Item])

      case deletion(items: [Item])

      case update(items: [Item])

}

Then, the observing object can receive the concrete information of what happened in a very clean way. This could easily be extended by adding oldValue and newValue, too.