SwiftLint valuable opt-in rules to improve your code

SwiftLint is a tool by Realm to enforce Swift style and conventions. It’s proven to be adopted by a lot of developer with over 10.000 stars on Github.

149 Rules are available for you to use from which a lot are enabled by default. In this post, we’re going over some valuable rules which are not enabled by default.

The great thing about SwiftLint is that it keeps itself up to date with a lot of contributors. The new boolean toggle() is introduced in Swift 4.2 and already adopted in a rule to enforce the usage of this new method.

convenience_type

Avoid instantiation by using a caseless enum for hosting only static members.

enum Math { // enum
    public static let pi = 3.14
}

empty_count

This rule can potentially improve performance, especially with iterating over large collections.

[Int]().isEmpty

empty_string

Avoiding instantiation of an empty String by using isEmpty over "".

myString.isEmpty

fatal_error_message

A fatalError is often used to prevent invalid states and to help you debug your code. A fatalError is most likely easier to understand by enforcing a message within the body.

fatalError("This method is unsupported, use init() instead")

file_name

Readability inside your projects is important for navigation and makes it easier to hand over your project to a colleague. This is a lot less efficient when the file system is not in sync with the class. This rule enforces you to have the same file name as the defined class within the file.

first_where

Performance is improved by using .first(where:) over .filter { }.first in collections to prevent iterating over the whole collection.

myNumbers.first(where: { $0 % 2 == 0 })

modifier_order

Consistency throughout your project improves readability overall. This rule enforces the order of modifiers by requiring override before public, public before final and so on.

prohibited_interface_builder

This rule is interesting if you’re on a team which has decided to not use the interface builder. It disallows the usage of @IBOutlet and @IBAction.

If you do use the interface builder

The rules private_action and private_outlet are great when you do use the interface builder. It keeps your UI code closed within the implementation class and it avoids leaking UIKit to higher layers.

toggle_bool

The great thing about SwiftLint is that it keeps itself up to date with a lot of contributors. The new boolean toggle() is introduced in Swift 4.2 and already adopted in a rule to enforce the usage of this new method.

unused_private_declaration

It is important to keep your codebase clean. This rule prevents unused private declarations and allows you to remove unused code.

Other rules worth to check out

Not all rules were worth to go over in detail, but some are still worth to check out. – fallthroughidentical_operandsjoined_default_parameterunavailable_function

A list of all rules can be found in the Github Repository