Swiftpack.co - Package - realm/SwiftLint

SwiftLint

A tool to enforce Swift style and conventions, loosely based on GitHub's Swift Style Guide.

SwiftLint hooks into Clang and SourceKit to use the AST representation of your source files for more accurate results.

Test Status codecov.io

This project adheres to the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to info@realm.io.

Language Switch: 中文, 한국어.

Installation

Using Homebrew:

brew install swiftlint

Using CocoaPods:

Simply add the following line to your Podfile:

pod 'SwiftLint'

This will download the SwiftLint binaries and dependencies in Pods/ during your next pod install execution and will allow you to invoke it via ${PODS_ROOT}/SwiftLint/swiftlint in your Script Build Phases.

This is the recommended way to install a specific version of SwiftLint since it supports installing a pinned version rather than simply the latest (which is the case with Homebrew).

Note that this will add the SwiftLint binaries, its dependencies' binaries and the Swift binary library distribution to the Pods/ directory, so checking in this directory to SCM such as git is discouraged.

Using Mint:

$ mint run realm/SwiftLint

Using a pre-built package:

You can also install SwiftLint by downloading SwiftLint.pkg from the latest GitHub release and running it.

Compiling from source:

You can also build from source by cloning this project and running git submodule update --init --recursive; make install (Xcode 9.0 or later).

Usage

Presentation

To get a high-level overview of recommended ways to integrate SwiftLint into your project, we encourage you to watch this presentation or read the transcript:

Presentation

Xcode

Integrate SwiftLint into an Xcode scheme to get warnings and errors displayed in the IDE. Just add a new "Run Script Phase" with:

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

Alternatively, if you've installed SwiftLint via CocoaPods the script should look like this:

"${PODS_ROOT}/SwiftLint/swiftlint"

Format on Save Xcode Plugin

To run swiftlint autocorrect on save in Xcode, install the SwiftLintXcode plugin from Alcatraz.

⚠ ️This plugin will not work with Xcode 8 or later without disabling SIP. This is not recommended.

AppCode

To integrate SwiftLint with AppCode, install this plugin and configure SwiftLint's installed path in the plugin's preferences. The autocorrect action is available via ⌥⏎.

Atom

To integrate SwiftLint with Atom, install the linter-swiftlint package from APM.

fastlane

You can use the official swiftlint fastlane action to run SwiftLint as part of your fastlane process.

swiftlint(
  mode: :lint,                            # SwiftLint mode: :lint (default) or :autocorrect
  executable: "Pods/SwiftLint/swiftlint", # The SwiftLint binary path (optional). Important if you've installed it via CocoaPods
  output_file: "swiftlint.result.json",   # The path of the output file (optional)
  reporter: "json",                       # The custom reporter to use (optional)
  config_file: ".swiftlint-ci.yml",       # The path of the configuration file (optional)
  ignore_exit_status: true                # Allow fastlane to continue even if SwiftLint returns a non-zero exit status
)

Command Line

$ swiftlint help
Available commands:

   autocorrect  Automatically correct warnings and errors
   help         Display general or command-specific help
   lint         Print lint warnings and errors for the Swift files in the current directory (default command)
   rules        Display the list of rules and their identifiers
   version      Display the current version of SwiftLint

Run swiftlint in the directory containing the Swift files to lint. Directories will be searched recursively.

To specify a list of files when using lint or autocorrect (like the list of files modified by Xcode specified by the ExtraBuildPhase Xcode plugin, or modified files in the working tree based on git ls-files -m), you can do so by passing the option --use-script-input-files and setting the following instance variables: SCRIPT_INPUT_FILE_COUNT and SCRIPT_INPUT_FILE_0, SCRIPT_INPUT_FILE_1...SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT}.

These are same environment variables set for input files to custom Xcode script phases.

Working With Multiple Swift Versions

SwiftLint hooks into SourceKit so it continues working even as Swift evolves!

This also keeps SwiftLint lean, as it doesn't need to ship with a full Swift compiler, it just communicates with the official one you already have installed on your machine.

You should always run SwiftLint with the same toolchain you use to compile your code.

You may want to override SwiftLint's default Swift toolchain if you have multiple toolchains or Xcodes installed.

Here's the order in which SwiftLint determines which Swift toolchain to use:

  • $XCODE_DEFAULT_TOOLCHAIN_OVERRIDE
  • $TOOLCHAIN_DIR or $TOOLCHAINS
  • xcrun -find swift
  • /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
  • /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
  • ~/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
  • ~/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain

sourcekitd.framework is expected to be found in the usr/lib/ subdirectory of the value passed in the paths above.

You may also set the TOOLCHAINS environment variable to the reverse-DNS notation that identifies a Swift toolchain version:

$ TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint autocorrect

On Linux, SourceKit is expected to be located in /usr/lib/libsourcekitdInProc.so or specified by the LINUX_SOURCEKIT_LIB_PATH environment variable.

Swift Version Support

Here's a reference of which SwiftLint version to use for a given Swift version.

| Swift version | Last supported SwiftLint release | | ------------- | -------------------------------- | | Swift 1.x | SwiftLint 0.1.2 | | Swift 2.x | SwiftLint 0.18.1 | | Swift 3.x | Latest | | Swift 4.x | Latest |

Rules

Over 75 rules are included in SwiftLint and the Swift community (that's you!) continues to contribute more over time. Pull requests are encouraged.

You can find an updated list of rules and more information about them in Rules.md.

You can also check Source/SwiftLintFramework/Rules directory to see their implementation.

Opt-In Rules

opt_in_rules are disabled by default (i.e., you have to explicitly enable them in your configuration file).

Guidelines on when to mark a rule as opt-in:

  • A rule that can have many false positives (e.g. empty_count)
  • A rule that is too slow
  • A rule that is not general consensus or is only useful in some cases (e.g. force_unwrapping)

Disable rules in code

Rules can be disabled with a comment inside a source file with the following format:

// swiftlint:disable <rule1> [<rule2> <rule3>...]

The rules will be disabled until the end of the file or until the linter sees a matching enable comment:

// swiftlint:enable <rule1> [<rule2> <rule3>...]

For example:

// swiftlint:disable colon
let noWarning :String = "" // No warning about colons immediately after variable names!
// swiftlint:enable colon
let hasWarning :String = "" // Warning generated about colons immediately after variable names

It's also possible to modify a disable or enable command by appending :previous, :this or :next for only applying the command to the previous, this (current) or next line respectively.

For example:

// swiftlint:disable:next force_cast
let noWarning = NSNumber() as! Int
let hasWarning = NSNumber() as! Int
let noWarning2 = NSNumber() as! Int // swiftlint:disable:this force_cast
let noWarning3 = NSNumber() as! Int
// swiftlint:disable:previous force_cast

Run swiftlint rules to print a list of all available rules and their identifiers.

Configuration

Configure SwiftLint by adding a .swiftlint.yml file from the directory you'll run SwiftLint from. The following parameters can be configured:

Rule inclusion:

  • disabled_rules: Disable rules from the default enabled set.
  • opt_in_rules: Enable rules not from the default set.
  • whitelist_rules: Acts as a whitelist, only the rules specified in this list will be enabled. Can not be specified alongside disabled_rules or opt_in_rules.
disabled_rules: # rule identifiers to exclude from running
  - colon
  - comma
  - control_statement
opt_in_rules: # some rules are only opt-in
  - empty_count
  # Find all the available rules by running:
  # swiftlint rules
included: # paths to include during linting. `--path` is ignored if present.
  - Source
excluded: # paths to ignore during linting. Takes precedence over `included`.
  - Carthage
  - Pods
  - Source/ExcludedFolder
  - Source/ExcludedFile.swift

# configurable rules can be customized from this configuration file
# binary rules can set their severity level
force_cast: warning # implicitly
force_try:
  severity: warning # explicitly
# rules that have both warning and error levels, can set just the warning level
# implicitly
line_length: 110
# they can set both implicitly with an array
type_body_length:
  - 300 # warning
  - 400 # error
# or they can set both explicitly
file_length:
  warning: 500
  error: 1200
# naming rules can set warnings/errors for min_length and max_length
# additionally they can set excluded names
type_name:
  min_length: 4 # only warning
  max_length: # warning and error
    warning: 40
    error: 50
  excluded: iPhone # excluded via string
identifier_name:
  min_length: # only min_length
    error: 4 # only error
  excluded: # excluded via string array
    - id
    - URL
    - GlobalAPIKey
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, junit, html, emoji)

You can also use environment variables in your configuration file, by using ${SOME_VARIABLE} in a string.

Defining Custom Rules

You can define custom regex-based rules in you configuration file using the following syntax:

custom_rules:
  pirates_beat_ninjas: # rule identifier
    included: ".*\\.swift" # regex that defines paths to include during linting. optional.
    excluded: ".*Test\\.swift" # regex that defines paths to exclude during linting. optional
    name: "Pirates Beat Ninjas" # rule name. optional.
    regex: "([n,N]inja)" # matching pattern
    match_kinds: # SyntaxKinds to match. optional.
      - comment
      - identifier
    message: "Pirates are better than ninjas." # violation message. optional.
    severity: error # violation severity. optional.
  no_hiding_in_strings:
    regex: "([n,N]inja)"
    match_kinds: string

This is what the output would look like:

You can filter the matches by providing one or more match_kinds, which will reject matches that include syntax kinds that are not present in this list. Here are all the possible syntax kinds:

  • argument
  • attribute.builtin
  • attribute.id
  • buildconfig.id
  • buildconfig.keyword
  • comment
  • comment.mark
  • comment.url
  • doccomment
  • doccomment.field
  • identifier
  • keyword
  • number
  • objectliteral
  • parameter
  • placeholder
  • string
  • string_interpolation_anchor
  • typeidentifier

Nested Configurations

SwiftLint supports nesting configuration files for more granular control over the linting process.

  • Include additional .swiftlint.yml files where necessary in your directory structure.
  • Each file will be linted using the configuration file that is in its directory or at the deepest level of its parent directories. Otherwise the root configuration will be used.
  • excluded and included are ignored for nested configurations.

Auto-correct

SwiftLint can automatically correct certain violations. Files on disk are overwritten with a corrected version.

Please make sure to have backups of these files before running swiftlint autocorrect, otherwise important data may be lost.

Standard linting is disabled while correcting because of the high likelihood of violations (or their offsets) being incorrect after modifying a file while applying corrections.

License

MIT licensed.

About

SwiftLint is maintained and funded by Realm Inc. The names and logos for Realm are trademarks of Realm Inc.

We :heart: open source software! See our other open source projects, read our blog, or say hi on twitter (@realm).

Github

link
Stars: 8221
Help us keep the lights on

Releases

0.24.0 - Nov 10, 2017

Breaking
Enhancements
  • Add sorted_first_last opt-in rule to encourage using min() or max() over sorted().first or sorted().last.
    Tom Quist #1932

  • Add quick_discouraged_focused_test opt-in rule which warns against focused tests in Quick tests.
    Ornithologist Coder #1905

  • Add override_in_extension opt-in rule that warns against overriding declarations in an extension.
    Marcelo Fabri #1884

  • Add [f,x]{describe, context, itBehavesLike} to quick_discouraged_call rule.
    Ornithologist Coder #1903

  • Add quick_discouraged_pending_test opt-in rule which warns against pending tests in Quick tests.
    Ornithologist Coder #1909

  • Speed up equality tests for [Rule] and Configuration values.
    JP Simard

  • Make Configuration conform to Hashable.
    JP Simard

  • Speed up reading cached results by about 200%.
    JP Simard

  • Add catch to the statements checked by the control_statement rule.
    JP Simard

  • Make sorted_imports correctable.
    Samuel Susla JP Simard #1822

  • Make sorted_imports only validate within "groups" of imports on directly adjacent lines.
    Samuel Susla JP Simard #1822

Bug Fixes
  • Extend first_where and contains_over_first_not_nil rules to also detect cases where calls to filter and first are parenthesized.
    Tom Quist

  • Correct equality tests for Configuration values. They previously didn't account for warningThreshold or cachePath.
    JP Simard

  • Fix false positive in multiline_parameters rule when parameter is a closure with default value.
    Ornithologist Coder #1912

  • Fix caching on Linux.
    JP Simard

  • Fix crashes due to races.
    JP Simard

  • Fix String.characters deprecation warnings when compiling with Swift 4.0.2.
    JP Simard

0.23.1 - Oct 10, 2017

Breaking
  • None.
Enhancements
  • None.
Bug Fixes
  • Fix false positive in array_init rule when using a map that doesn't take a closure.
    Marcelo Fabri #1878

  • superfluous_disable_command rule can now be disabled as expected when using // swiftlint:disable superfluous_disable_command.
    Marcelo Fabri #1890

0.23.0 - Oct 4, 2017

Breaking
  • None.
Enhancements
  • Fix csv reporter to output records with new lines.
    atetlaw

  • Add contains_over_first_not_nil rule to encourage using contains over first(where:) != nil.
    Samuel Susla #1514

  • Add fallthrough rule that flags usage of fallthrough.
    Marcelo Fabri #1834

  • Improve colon rule to catch violations in dictionary types (e.g. [String: Int]), when using Any and on function calls.
    Marcelo Fabri #1074 #1389

  • Add switch_case_alignment rule to validate that case and default statements are vertically aligned with their enclosing switch statement.
    Austin Lu

  • Add array_init opt-in rule to validate that Array(foo) should be preferred over foo.map({ $0 }).
    Marcelo Fabri #1271

  • Truncate long configuration console descriptions to fit in the console window when running swiftlint rules.
    JP Simard #1002

  • Add multiline_arguments opt-in rule that warns to either keep all the arguments of a function call on the same line, or one per line.
    Marcel Jackwerth

  • Add unneeded_break_in_switch rule to validate that no extra breaks are added in switch statements.
    Marcelo Fabri #1870

  • Add literal_expression_end_indentation opt-in rule to validate that array and dictionary literals ends have the same indentation as the line that started them.
    Marcelo Fabri #1435

Bug Fixes
  • Improve how opening_brace rule reports violations locations.
    Marcelo Fabri #1811

  • Fix false negatives in unneeded_parentheses_in_closure_argument rule when using capture lists.
    Marcelo Fabri #1817

  • Fix handling of attributes (lazy, objc, etc.) for the let_var_whitespace rule.
    David Catmull #1770 #1812

  • Fix false positives in for_where rule when using if var inside for.
    Marcelo Fabri #1838

  • Fix false positive in class_delegate_protocol rule when using Swift 4.0.1.
    Marcelo Fabri #1856

  • Print multi-line configuration values in a single line when running swiftlint rules to avoid breaking the table format.
    JP Simard #1002

  • Ignore SwiftLint commands (swiftlint:(disable|enable)) in file_header rule, making it work better with superfluous_disable_command rule.
    Marcelo Fabri #1810

  • Fix false negatives in generic_type_name, identifier_name and type_name rules when using allowed_symbols.
    Marcelo Fabri

0.22.0 - Aug 30, 2017

Breaking
Enhancements
  • Add is_disjoint rule to encourage using Set.isDisjoint(with:) over Set.intersection(_:).isEmpty.
    JP Simard

  • Add xctfail_message rule to enforce XCTFail calls to include a description of the assertion.
    Ornithologist Coder #1370

  • Add joined_default_parameter correctable opt-in rule to discourage explicit usage of the default separator.
    Ornithologist Coder #1093 #1757

  • Files with extensions other than .swift can now be used as arguments to --file when linting or autocorrecting.
    Marcelo Fabri #1721

  • Allow ()?, Void?, ()!, and Void! as return types in redundant_void_return rule.
    Ryan Booker #1761

  • Add single_test_class opt-in rule to validate that test files only contain a single QuickSpec or XCTestCase subclass.
    Ornithologist Coder #1779

  • Produce an error when a // swiftlint:disable command does not silence any violations.
    JP Simard #1102

  • Add quick_discouraged_call opt-in rule to discourage calls and object initialization inside 'describe' and 'context' block in Quick tests.
    Ornithologist Coder #1781

  • Invalidate cache when Swift version changes.
    Marcelo Fabri

  • Add pattern_matching_keywords opt-in rule to enforce moving let and var keywords outside tuples in a switch.
    Marcelo Fabri #202

  • Add explicit_enum_raw_value opt-in rule to allow refactoring the Swift API without breaking the API contract.
    Mazyod #1778

  • Add no_grouping_extension opt-in rule to disallow the use of extensions for code grouping purposes within the same file.
    Mazyod #1767

  • Improve syntactic_sugar violation message to be type-specific.
    Marcelo Fabri #1803

  • Add multiple_closures_with_trailing_closure rule that disallows trailing closure syntax when passing more than one closure argument to a function.
    Erik Strottmann #1801

Bug Fixes
  • Fix false positive on force_unwrapping rule when declaring local variable with implicity unwrapped type.
    Otávio Lima #1710

  • Fix the warning message and autocorrection of vertical_whitespace rule to display the maximum empty lines allowed if max_empty_lines is greater than 1.
    Hossam Ghareeb #1763

  • Fix for the wrong configuration being used when using --path and a configuration exists in a parent directory.
    Marcelo Fabri #1744

  • Fix false positive on unused_enumerated rule with complex variable bindings.
    Marcelo Fabri #1787

  • Fix incorrect violations and autocorrections on unneeded_parentheses_in_closure_argument rule that were generated in some cases (mainly when using chained method calls with closures).
    Marcelo Fabri

0.21.0 - Aug 1, 2017

Breaking
  • Xcode 8.3 or later and Swift 3.1 or later are required to build.
    Norio Nomura
Enhancements
  • Rules are now categorized as lint, idiomatic, style, metrics or performance. Currently this is just used for documentation purposes when you run swiftlint rules or swiftlint generate-docs.
    Marcelo Fabri

  • Add rules documentation generation.
    Marcelo Fabri #1078

  • Add private_over_fileprivate correctable rule to check for top-level usages of fileprivate and recommend private instead. This is in line with SE-0169's goal "for fileprivate to be used rarely". There is a also a new strict_fileprivate opt-in rule that will mark every fileprivate as a violation (especially useful with Swift 4).
    Jose Cheyo Jimenez Marcelo Fabri #1469 #1058

  • Add let_var_whitespace opt-in rule to enforce that let/var declarations should be separated from other statements by a single blank line.
    Uncommon #1461

  • Improve performance when linting and correcting on Linux, matching macOS behavior.
    JP Simard #1577

  • Don't trigger implicit_getter violations when attributes (such as mutating or @inline) are present.
    Marcelo Fabri #1309 #1589

  • Add --use-tabs option to AutoCorrectOptions, enabling formatting using tabs over spaces.
    Cody Winton #1327

  • Improve autocorrect performance by running it in parallel.
    Marcelo Fabri #1578

  • Support building with Xcode 9 beta 3 in Swift 3.2 mode.
    JP Simard

  • Add support for optional error severity level configuration.
    Jamie Edge Marcelo Fabri #1647

  • Add unneeded_parentheses_in_closure_argument opt-in correctable rule that warns against using parentheses around argument declarations in closures.
    Marcelo Fabri #1483

  • Add --disabled flag to swiftlint rules to print only rules that are not enabled in the configuration.
    Marcelo Fabri

  • Add ignore_comment_only_lines boolean configuration option to file_length rule. With the option enabled, file_length will ignore lines which have only comments.
    Samuel Susla #1165

  • Improve file_header rule description.
    Marcelo Fabri #1492

  • Add trailing_closure opt-in rule that validates that trailing closure syntax should be used whenever possible.
    Marcelo Fabri #54

  • Shebang (#!) in the beginning of a file is now ignored by all rules.
    Marcelo Fabri #1294

  • Add block_based_kvo rule that enforces the usage of the new block based KVO API added when linting with Swift 3.2 or later.
    Marcelo Fabri #1714

  • Make file_header rule ignore doc comments.
    Marcelo Fabri #1719

  • Allow using environment variables in a configuration file in the form of ${SOME_VARIABLE}. The variables will be expanded when the configuration is first loaded.
    Marcelo Fabri #1512

  • Treat yes, no, on and off as strings (and not booleans) when loading configuration files.
    Marcelo Fabri #1424

  • Add discouraged_direct_init rule that discourages direct initialization of certain types.
    Ornithologist Coder #1306

Bug Fixes
  • Fix false positive on redundant_discardable_let rule when using while statements.
    Marcelo Fabri #1669

  • Fix all custom rules not being applied when any rule is configured incorrectly.
    Jamie Edge #1586

  • Fix crash when using --config with a relative path and --path with a file.
    Marcelo Fabri #1694

  • Fix mark rule corrections generating invalid code in some cases.
    Marcelo Fabri #1029

  • Fix false positive in empty_enum_arguments rule when using wildcards and where clauses.
    Marcelo Fabri #1722

  • Fix false positive in large_tuple rule when using throwing closure.
    Liquidsoul

  • Make vertical_parameter_alignment more robust, fixing false positives and detecting previously missed violations.
    JP Simard #1488