Organizing your Swift classes

I’ve always used Xcode annotations to organize my code and improve its readability. I finally ended up with a pattern I use in almost every class, which allows me to work more efficiently.


I try to have a good organization in all my classes, it helps me quickly find what I’m searching for.

Whatever the pattern you choose, what is important is to always reuse the same organization in your project. You can then open any file and go directly to the section you are interested in because you know where it is.


Having had a look at the WWDC 2015 sample code about advanced collection view, I took out a pattern for annotations in classes (even if I know, nobody likes Apple sample codes).

This pattern is mostly valid for view controllers and views, which are the most common classes in a regular iOS project. But you can still reuse parts of it in other classes.

  1. Types: contains enumerations,
  2. Properties: all properties (IBOutlet, let, var, etc.),
  3. View Life Cycle: all viewDid… methods,
  4. Lifetime: init and deinit methods,
  5. Layout: layoutSubviews… methods,
  6. Setup: view and data initialization,
  7. Actions: actions done by the user (IBAction, UIGestureRecognizer, etc.),
  8. UIStoryboardSegue Handling: prepareForSegue… methods,
  9. Notifications: notifications methods,
  10. Convenience: interface update, all convenience methods (e.g. cellForType),
  11. UI…Delegate: all delegate methods.

Then inside each annotation, I write my methods in the order they are called, as recommended by Uncle Bob in his book Clean Code.

Swift extensions

Swift has brought the possibility of using Swift extensions to organize the code into smaller bricks. I totally agree to use this method for protocol conformance:

<pre class="wp-block-code">```
class ViewController: UIViewController {
    // MARK: - Setup

    // Put all the setup methods here

    // MARK: - Actions

    // Put all the actions methods here

// MARK: UITableViewDelegate
extension ViewController: UITableViewDelegate { }

But you can go even further, as [Natasha The Robot]( suggested it, by using Swift extensions to group your methods: