Swiftpack.co - Package - realm/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.

Build 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: 中文, 한국어.


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 install 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 10.2 or later).

Known Installation Issues On MacOS Before 10.14.4

Starting with SwiftLint 0.32.0, if you get an error similar to dyld: Symbol not found: _$s11SubSequenceSlTl when running SwiftLint, you'll need to install the Swift 5 Runtime Support for Command Line Tools.

Alternatively, you can:

  • Update to macOS 10.14.4 or later
  • Install Xcode 10.2 or later at /Applications/Xcode.app
  • Rebuild SwiftLint from source using Xcode 10.2 or later



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:



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
  echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"

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


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.


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 ⌥⏎.


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


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

    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
    path: "/path/to/lint",                  # Specify path to lint (optional)
    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)
    files: [                                # List of files to process (optional)
    ignore_exit_status: true,               # Allow fastlane to continue even if SwiftLint returns a non-zero exit status (Default: false)
    quiet: true,                            # Don't print status logs like 'Linting ' & 'Done linting' (Default: false)
    strict: true                            # Fail on warnings? (Default: false)

Command Line

$ swiftlint help
Available commands:

   analyze         [Experimental] Run analysis rules
   autocorrect     Automatically correct warnings and errors
   generate-docs   Generates markdown documentation for all rules
   help            Display general or command-specific help
   lint            Print lint warnings and errors (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, autocorrect or analyze (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:

  • 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 | SwiftLint 0.25.1 | | Swift 4.0-4.1.x | SwiftLint 0.28.2 | | Swift 4.2.x | SwiftLint 0.35.0 | | Swift 5.0 | Latest |


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

Including the all keyword will disable all rules until the linter sees a matching enable comment:

// swiftlint:disable all // swiftlint:enable all

For example:

// swiftlint:disable all
let noWarning :String = "" // No warning about colons immediately after variable names!
let i = "" // Also no warning about short identifier names
// swiftlint:enable all
let hasWarning :String = "" // Warning generated about colons immediately after variable names
let y = "" // Warning generated about short identifier 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.


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.
  • analyzer_rules: This is an entirely separate list of rules that are only run by the analyze command. All analyzer rules are opt-in, so this is the only configurable rule list (there is no disabled/whitelist equivalent).
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
  - Source/*/ExcludedFile.swift # Exclude files with a wildcard
analyzer_rules: # Rules run by `swiftlint analyze` (experimental)
  - explicit_self

# configurable rules can be customized from this configuration file
# binary rules can set their severity level
force_cast: warning # implicitly
  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
  - 300 # warning
  - 400 # error
# or they can set both explicitly
  warning: 500
  error: 1200
# naming rules can set warnings/errors for min_length and max_length
# additionally they can set excluded names
  min_length: 4 # only warning
  max_length: # warning and error
    warning: 40
    error: 50
  excluded: iPhone # excluded via string
  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, sonarqube, markdown)

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 your configuration file using the following syntax:

  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.
    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

If using custom rules alongside a whitelist, make sure to add custom_rules as an item under whitelist_rules.

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.


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.

Analyze (experimental)

The experimental swiftlint analyze command can lint Swift files using the full type-checked AST. The compiler log path containing the clean swiftc build command invocation (incremental builds will fail) must be passed to analyze via the --compiler-log-path flag. e.g. --compiler-log-path /path/to/xcodebuild.log

This can be obtained by running xcodebuild -workspace {WORKSPACE}.xcworkspace -scheme {SCHEME} > xcodebuild.log with a clean DerivedData folder.

This command and related code in SwiftLint is subject to substantial changes at any time while this feature is marked as experimental. Analyzer rules also tend to be considerably slower than lint rules.


MIT licensed.


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).


Stars: 12528
Help us keep the lights on


0.35.0 - Sep 3, 2019

This is the last release to support building with Swift 4.2.x.


  • None.


  • None.


  • Type name rules considers SwiftUI template code.
    atfelix #2791

  • Add no_space_in_method_call rule to validate that there're no spaces between the method name and parentheses in a method call.
    Marcelo Fabri

  • Add contains_over_filter_count opt-in rule to warn against using expressions like filter(where:).count > 0 instead of contains(where:).
    Marcelo Fabri #2803

  • Add contains_over_filter_is_empty opt-in rule to warn against using expressions like filter(where:).isEmpty instead of contains(where:).
    Marcelo Fabri

  • Add empty_collection_literal opt-in rule to prefer using isEmpty to comparison to [] or [:].
    Colton Schlosser #2807

Bug Fixes

0.34.0 - Jul 19, 2019


  • To enable collecting rules, many breaking changes to SwiftLintFramework's public API were made the Linter type was significantely changed, and a new CollectedLinter type was introduced. Many public SwiftLintFramework APIs that interacted with Linter have also been affected. More new types and protocols were added such as RuleStorage, AnyCollectingRule, CollectingRule, CollectingCorrectableRule. We are not aware of any significant users of the SwiftLintFramework library, so if you are affected by this, please reach out to SwiftLint contributors by filing a GitHub issue about your use case.
    Elliott Williams JP Simard


  • Add a two-stage CollectingRule protocol to support rules that collect data from all files before validating. Collecting rules implement a collect method which is called once for every file, before any file is checked for violations. By collecting, rules can be written which validate across multiple files for things like unused declarations.
    Elliott Williams #2431

  • Add a new unused_declaration analyzer rule to lint for unused declarations. By default, detects unused fileprivate, private and internal declarations. Configure the rule with include_public_and_open: true to also detect unused public and open declarations.
    JP Simard

  • Completely remove the unused_private_declaration rule. Please use unused_declaration instead.
    JP Simard


  • None.

Bug Fixes

  • None.

0.33.1 - Jul 8, 2019


  • None.


  • None.


  • Significantly improve performance when running with a large number of cached configurations or when running with many cached results. This was done by splitting each configuration to have its own cache and by encoding the cache as a binary property list instead of json.
    Colton Schlosser JP Simard

  • Several public types in SwiftLintFramework have added Codable conformance: Location, RuleDescription, RuleKind, StyleViolation, SwiftVersion, ViolationSeverity.
    JP Simard

  • Print full relative path to file in log output when it matches the file name of another path being linted.
    Keith Smiley

Bug Fixes

  • Don't trigger vertical_parameter_alignment violations when using parameters with attributes such as @ViewBuilder in function declarations.
    Marcelo Fabri #2792

  • Fix false positive in function_default_parameter_at_end rule when using a closure parameter with default value.
    Marcelo Fabri #2788

0.33.0 - Jun 2, 2019


  • Remove the weak_computed_property rule. Please see linked issue for discussion and rationale.
    JP Simard #2712


  • None.


  • Add " - " delimiter to allow commenting SwiftLint commands without triggering superfluous_disable_command.
    Kevin Randrup

  • Make testSimulateHomebrewTest() test opt-in because it may fail on unknown condition. Set SWIFTLINT_FRAMEWORK_TEST_ENABLE_SIMULATE_HOMEBREW_TEST environment variable to test like:

    swift test --filter testSimulateHomebrewTest

    Norio Nomura

  • Add option to configure how nested types should be separated in file names by introducting nested_type_separator configuration for the file_name rule.
    Frederick Pietschmann #2717

  • Add unowned_variable_capture opt-in rule to warn against unowned captures in closures when using Swift 5.
    Marcelo Fabri #2097

  • Don't trigger a no_fallthrough_only violation if next case is an @unknown default.
    Marcelo Fabri #2696

  • Add duplicate_enum_cases rule to validate that an enum doesn't contain duplicated cases, as it's impossible to switch on it (see SR-10077 for details).
    Marcelo Fabri #2676

  • Add legacy_multiple opt-in rule to warn against using the remainder operator (%) checking for a remainder of zero when using Swift 5.
    Marcelo Fabri #2612

Bug Fixes

  • Don't trigger redundant_void_return violations when using subscript as the return type is required.
    Marcelo Fabri

  • Skip module import if cursor info is missing module info.
    alvarhansen #2746

  • Don't trigger file_types_order violations in files only containing extensions.
    Sam Rayner #2749

  • Force-unwrapping self should trigger a violation of the force_unwrapping rule.
    Dalton Claybrook #2759

0.32.0 - Apr 29, 2019

This release has improved support for building and running SwiftLint using Swift 5, adds seven new (super useful) rules and fixes a number of false positives or missing violations.


  • None.


  • None.


  • Add reduce_boolean rule to prefer simpler constructs over reduce(Boolean).
    Xavier Lowmiller #2675

  • Add nsobject_prefer_isequal rule to warn against implementing == on an NSObject subclass as calling isEqual (i.e. when using the class from Objective-C) will not use the defined == method.
    Matthew Healy #2663

  • Add reduce_into opt-in rule to encourage the use of reduce(into:_:) instead of reduce(_:_:) which is less performant.
    Dalton Claybrook #2658

  • Remove @ mark to fix invalid link in Rules.md.
    Hiroki Nagasawa #2669

  • Add new opt-in rule file_types_order to specify how the types in a file should be sorted.
    Cihat Gündüz #2294

  • Add new opt-in rule type_contents_order to specify the order of subtypes, properties, methods & more within a type.
    Cihat Gündüz #2294

  • Add nslocalizedstring_require_bundle rule to ensure calls to NSLocalizedString specify the bundle where the strings file is located.
    Matthew Healy #2595

  • contains_over_first_not_nil rule now also checks for firstIndex(where:).
    Marcelo Fabri #2678

  • Add unused_capture_list rule to ensure that all references in a closure capture list are used.
    Dalton Claybrook #2715

  • SwiftLint can now be compiled using Xcode 10.2.
    Marcelo Fabri Norio Nomura #2693

Bug Fixes

  • Fix bug where SwiftLint ignores excluded files list in a nested configuration file.
    Dylan Bruschi #2447

  • colon rule now catches violations when declaring generic types with inheritance or protocol conformance.
    Marcelo Fabri #2628

  • discarded_notification_center_observer rule now checks if the observer is added to any collection or passed to a function before triggering the violation.
    jsloop42 #2684

  • Fix false positives on number_separator when the number is wrapped in parentheses.
    Dalton Claybrook #2683

  • Fix false positives on sorted_first_last when calling firstIndex and lastIndex method. Taiki Komaba #2700

  • Fix crash when running on Linux with Swift 5 without specifying a --path value or specifying an empty string.
    Keith Smiley #2703

  • Fix false positives on explicit_acl and explicit_top_level_acl rules when declaring extensions that add protocol conformances with Swift 5.
    Marcelo Fabri #2705

  • Let disable all command override superfluous_disable_command rule.
    Frederick Pietschmann #2670

  • Fix issues in explict_acl, redundant_set_access_control and explicit_top_level_acl rules when using Swift 5.
    Marcelo Fabri #2694