Style is important when writing code. Following conventions and guidelines helps tell the story of our code to our team and our future-selves. Today we'll learn about SwiftLint, a tool from Realm that can help us enforce Swift conventions and best practices. Let's get started.
brew install swiftlint
Now, we can run
swiftlint rules at the command line to see all the different convetions and standards that will be enforced. We can also run
swiftlint lint in the root directory of our project to see what rules we're breaking right in the terminal.
Our next step is to add SwiftLint as a build phase to our project.
We'll head over to our project's settings, then to the Build Phases tab. We'll click the + button to add a** new “Run Script” phase**. We'll name it “SwiftLint” and give it the follow script content:
if which swiftlint > /dev/null; then swiftlint else echo “Download SwiftLint: https://github.com/realm/SwiftLint" fi
Now when we build our project, SwiftLint will let us know via regular Errors and Warnings in Xcode when there's something to fix.
We can configure how SwiftLint behaves in complete detail by creating a new file called
.swiftlint.yml and putting it in the root directory of our project. We can fill out this file to customize (for example) which conventions are enforced:
disabled_rules: - colon - control_statement
We can disable rules “in-line” in our code with special comments:
// swiftlint:disable colon let noWarning :String = "" // No warning about colon placement // swiftlint:enable colon let yesWarning :String = "" // Warning generated
Finally, SwiftLint can correct some violations (trailing_newline, trailing_semicolon, etc.). Just run
More info about SwiftLint can be found at git.io/swiftlint