SwiftLint is a tool built and maintained by Realm Inc for enforcing checks on Swift code styles and rules, basically based on GitHub’s Swift Code Style Guide.

Personal use is recorded here, as detailed in the official Chinese document.

Mac / / note:

Install SwiftLint

Using Homebrew to install global configuration, open terminal and enter the following command:

brew install swiftlint

Second, in the project use

After installing SwiftLint, you need to configure scripts in the project to automatically detect code specifications. The configuration steps are as follows:

Script:

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

After the configuration is complete, SwiftLint will perform a specification check at project compile time and give a yellow warning or red error.

3. Custom configuration

Support for custom rules for projects as well as rules for specific files.

1. Create a configuration file for the project

  • Enter the project directory in terminal
  • New rule file:touch .swiftlint.yml
  • Open:open .swiftlint.yml
  • Edit custom rules, for example:
excluded:  Path ignored when performing linting. The priority is higher than 'included'.
  - Pods # ignore third-party libraries dumped through CocoaPods

  # -source /ExcludedFolder # Specify the directory under the exact path
  # # - Source/ExcludedFile. Swift, accurate path under the specified file

disabled_rules: # rule excluded at execution time
  - identifier_name    The name of the Json field must be in conflict with the name of the Json field
  - trailing_whitespace   # Every empty line must have no Spaces. This will conflict with the Spaces generated by Xcode after line wrapping

force_cast: warning # Type judgment
force_try: warning # try statement

cyclomatic_complexity: 20 # Code complexity, default is 10

line_length:  # Single-line code length, default error 120
  warning: 120
  error: 200

file_length:  # file length
  warning: 500
  error: 1200

function_body_length: # Function body length
  warning: 100
  error: 300

Copy the code
  • save

2. Apply rules to a file or function

A rule can be turned off by defining a comment in a source file in the following format: // swiftLint :disable

This rule is disabled until the end of the file or until a matching comment of the following format is defined: // swiftLint :enable