Please use MARK pre-processor directive

In Xcode, the // MARK: and // MARK: - pre-processor directive allows you to create separations in your Swift source files. This directive does not change the behavior of your code, it’s just here to help organizing it.

When, why and how should I use them?

You should use marks to separate the code of your source file into sections. These sections should represent logic units and/or group of declarations (outlets / functions) that are going with each other.

By grouping your code this way, you will often come to realize something doesn’t belong to any category: in this case, it probably belongs elsewhere than in this class, this is a good signal that you could refactor this function or piece of code into another file / class.

Additionally if you end up having groups named “utils” or “utilities”, it’s again a good signal a refactor is needed.

Finally in Xcode 11, the mini-map will highlight these marks, using them will therefore become more important than ever.

Difference between // MARK: and // MARK: –

The difference is subtle but exists, with the added - at the end of // MARK:, Xcode symbol explorer adds a separator before the mark, so when clicking on your symbols in this bar:

it will look like this:

instead of this:

I personally only use the // MARK: - syntax.

Create a snippet

Creating a Xcode snippet allows you to add marks faster and ensure you are using a consistent format thanks to auto-completion.

To create a snippet in Xcode:

  1. from the status bar, click on “Editor” then “Create Code Snippet”
  2. give a name to your snippet (eg: MARK)
  3. Choose a “Completion Shortcut” keyword, I use lowercase “mark” so that writing the beginning of the word triggers the auto-completion
  4. Choose “All” for Completion Scopes
  5. Enter // MARK: - <#category#> in the text box

To use the snippet, start tapping “mark” in your code editor and let the auto-completion do the work.

Leave a Reply

Your email address will not be published. Required fields are marked *