Otávio C.

SwiftLint

As the name suggests, SwiftLint is a tool used by the Swift community to enforce certain rules, styles, and conventions. Although I use SwiftLint in my own projects, its real value shows in a shared codebase. Code reviews are expensive, requiring a lot of back-and-forth between the engineer who submitted the code and the reviewers. Quite frequently, the suggestions from reviewers are about 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, approximately 10% of the total, and a number of improvements.

If I had to pick a favorite rule from the ones I implemented, it would be Multiline Parameters. This was the first rule I implemented and one of the first I enable in a new project. It requires parameters to be either all on the same line or one per line. An example that triggers a violation:

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

Parameters on a single line, or one per line, respect the rule:

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

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

Combined with multiline_parameters_brackets, it enforces the pattern below for functions and methods:

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

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

Two other rules I wrote and enable as soon as a project starts are Discouraged Optional Boolean and Discouraged Optional Collection, both meant to enforce clearer interfaces. In most cases, non-optional booleans and collections are enough: true or false, a collection with or without items. For the remaining cases, enums with associated values can cover the absence of information or the different states.

That's the value of SwiftLint. Not the rules themselves, but the fact that nobody has to remember them. Style stops being a review topic and becomes a build step, leaving the discussion for what actually deserves it.

#Handpick #Swift