Divide Class into Class + Extension (Swift Refactoring)

Context: You have a class that implements one or more protocols. The class has become long, and it’s confusing to understand what parts are there for the protocols, and what parts are for the class’ internal needs.

Divide Class into Class + Extension

Solution: Divide the class into the main class plus an extension. This lets you segregate the parts implementing a protocol from the rest of the class. You can optionally pull the extension into a separate file (typically named Class+Protocol.swift).

Consequences: Each part is simpler on its own. But notice that you haven’t reduced the total size of the class. You may want to explore further ways to reduce its size.

Mechanics

  1. Declare an empty extension implementing the protocol; remove the protocol declaration from the class. (If the class supports multiple protocols, work one at a time.)
class X : Protocol {
   // a mix of internal and protocol-compatible properties & methods
}
      =>
class X {
   // all properties & methods as before
}

extension X: Protocol {
}

2. Move protocol-required properties or methods from the class to the extension. You can work one or a few at a time. Refer to the protocol definition to understand which elements are involved.

3. If there are properties or methods used only to support protocol conformance, pull them into the extension too.

4. Optionally pull the extension into a separate file (typically MyClass+Extension.swift).

5. Explore why the class has become so large – are there other things that can be split out?