Otávio’s blog

SwiftLint

As the name suggests, SwiftLint is a tool used by the Swift community to enforce certain rules, styles, and conventions. And although I use SwiftLint in my own projects, its real value shows when used in a shared codebase. Code reviews, for instance, are expensive, requiring a lot of back-and-forth between the engineer who submitted the code for review and the reviewers. Quite frequently, the suggestions from reviewers are related to coding style and conventions, wasting everyone's time.

Team opinion should be automated whenever possible, reducing the time wasted in code reviews and leaving the practice for what really matters: logic, performance, code design, and architecture.

I first looked into SwiftLint when I found myself repeating the same feedback in different pull requests. Most of the rules needed by the team were part of SwiftLint already, but some conventions we had were missing. That's when I decided to contribute to the project, resulting in several new rules (10% approximately) and improvements.

If I had to pick a favorite rule from the ones I implemented, it would be the SwiftLint Multiline Parameter rule. This was the first rule I implemented and one of the first I enabled in a new project. The rule enforces that parameters should be either on the same line or one per line. An example that throws a violation:

func foo(_ param1: Int,
          param2: Int, param3: Int) -> (Int) -> Int {}

While all parameters on the same line or one per line respect the rule:

func foo(param1: Int, param2: Bool, param3: [String]) { }

func foo(param1: Int,
         param2: Bool,
         param3: [String]) { }

When combined with the rule multiline_parameters_brackets, it enforces the pattern below for functions and methods:

func foo(
    param1: String,
    param2: String,
    param3: String
)

Which is refactoring-safe, reducing the number of changes when a new parameter is added or removed from the interface. Kevlin Henney has a really good talk about code details and style called Seven Ineffective Coding Habits of Many Programmers where he touches on this topic.

Two other rules I wrote and enabled as soon as I can are Discouraged Optional Boolean and Discouraged Optional Collection to enforce more clear interfaces. In most cases, non-optional booleans and collections are enough (true/false, collection with/without items); for other cases, enums with associated values can be used to cover the absence of information or different states.

In conclusion, SwiftLint is an invaluable tool for maintaining code quality and consistency across Swift projects. By automating the enforcement of coding standards, it significantly reduces the time spent on style-related feedback during code reviews, allowing teams to focus on more critical aspects such as logic, performance, code design, and architecture.

#handpick #swift