Organizing your Swift code

How you organize your code says a lot about what kind of a developer you are. A lack of consistency and organization within your classes can cause problems down the line. Save yourself trouble and organize your methods into useful, easy to read sections. This is especially important as your code base grows in size with future upgrades to your app.

Before Swift, we used the #pragma mark preprocessor directive to logically organize our code. Pragma mark doesn’t work anymore, but luckily we have a few new options for code organization in the Swift programming language.  Organize your Swift code with the newest additions, MARK, TODO & FIXME.

Organizing Swift Code

In the latest Xcode, we have three options for organizing our code:
// MARK:
// TODO:
// FIXME:

MARK

Used to separate groups of methods with similar functionality. This allows you and others who are looking at your code to quickly jump between relevant sections. Think of this like the old #pragma mark preprocessor in Objective-C. This marker is generally used the most frequently of the three.

TODO

This marker is used to indicate portions of your code that needs to be completed.

FIXME

This marker indicates a portion of your code that needs review or revision.

Note: You must use two slashes to indicate a comment. The MARK, TODO & FIXME text must be in uppercase followed by a colon and then your description text. You can use these markers inside or outside of a method.

Is this required?

No, this often isn’t necessary when you only have a few methods in a class. However, on larger classes, it is good form to use MARK to organize your code and TODO & FIXME to indicate where changes need to be made in the future.

What does it actually do?

It just makes it easier to navigate around a class, for you and your co-workers. Placing these comments in your class will result in them showing on the method dropdown box. (See below).

Example screenshot

Organizing your Swift code

Example Code

The following code below shows how each section was separated using the MARK, TODO & FIXME comments.

//# MARK: - Text Methods

func printText(){

//Print text
println("Printing this line to the console")

}

func exportText(){

//Export text

}

func importText(){

//Import text

}

//# TODO: - Add social features

func exportToFacebook(){

//Facebook

}

// FIXME: - Bug in 2.0

func applyTextFormatting(){

let pi = 3.15

}

 
A note about MARK
Add a line between the colon and your description to insert a separator line. This helps to organize your code even more. The code and screenshot above make use of the MARK comment with a line included.

// MARK: – Text Methods (LINE)
// MARK: Text Methods (NO LINE)

This only works with the MARK comment.