Writing code, the Swift style


Different people have different styles of writing code. Working in a team means mixed styles, even when all developers are using a coding convention.

Writing code in Swift can sometimes lead to unneeded if let, downcasting or force unwrapping values.

An easy way to resolve these and many other issues is by introducing SwiftLint to the project. As stated on its GitHub page, SwiftLint is a

tool to enforce Swift style and conventions

Created by the good guys at Realm, this tools helps with keeping the code more consistent and clear.

Installation

You can install SwiftLint by

  • using homebrew
    brew install swiftlint
  • or by downloading and installing SwiftLint.pkg

Usage

To start using the tool, simply add a new Run Script Phase:

if which swiftlint >/dev/null; then
    swiftlint
else
    echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

There is also a nice way to automatically format the code on save in Xcode. To do so, you will need to install SwiftLintXcode plugin for Alcatraz

Rules configuration

SwiftLint allows for additional configuration, enabling and disabling of rules. To do so, create a .swiftlint.yml file in the root of the project. A complete list of the rules can be found on their GitHub page.

A simple list of rules I have set in one of my projects:

excluded:
  - Pods
disabled_rules:
  - line_length
variable_name:
  excluded:
    - id
    - to

It excludes SwiftLint checks for the Pods folder, disables line length check and allows short variable names (in this case id and to).

Once added to your project, you might get surprised of the result
Example - SwiftLint errors
This shows why it is good to add it from the beginning 🙂

When the project has been built, you can check and fix all issues from the Issues Navigator panel on the left side.

The warnings and errors generated by SwiftLint look like the standard ones you see from Xcode
Example - SwiftLint warning and error

Summary

Although you might get a lot of errors and warnings once you add SwiftLint to your project, it is completely worth the time and effort to introduce it to the project and fix the issues it finds. In case there are too many errors, it might be a good idea to disable all rules and enable them one by one and fixing small chunks of issues step by step. Using SwiftLint will also ensure that all the people in your team will comply with the rules that you configure. That’s why I will also use it from the beginning in my next projects.