- Notifications
You must be signed in to change notification settings - Fork0
A tool to enforce Swift style and conventions.
License
phlippieb/SwiftLint
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A tool to enforce Swift style and conventions, loosely based on the now archivedGitHub Swift Style Guide. SwiftLint enforces the style guide rules that are generally accepted by the Swift community. These rules are well described in popular style guides likeKodeco's Swift Style Guide.
SwiftLint hooks intoClang andSourceKit to use theAST representationof your source files for more accurate results.
This project adheres to theContributor Covenant Code of Conduct.By participating, you are expected to uphold this code. Please reportunacceptable behavior toinfo@realm.io.
UsingHomebrew:
brew install swiftlintUsingCocoaPods:
Simply add the following line to your Podfile:
pod'SwiftLint'
This will download the SwiftLint binaries and dependencies inPods/ during your nextpod install execution and will allow you to invoke it via${PODS_ROOT}/SwiftLint/swiftlintin your Script Build Phases.
This is the recommended way to install a specific version of SwiftLint since it supportsinstalling 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 binarylibrary distribution to thePods/ directory, so checking in this directory to SCM such asgit is discouraged.
UsingMint:
$ mint install realm/SwiftLintYou can also install SwiftLint by downloadingSwiftLint.pkg from thelatest GitHub release andrunning it.
You can also build and install from source by cloning this project and runningmake install (Xcode 15.0 or later).
Put this in yourMODULE.bazel:
bazel_dep(name="swiftlint",version="0.52.4",repo_name="SwiftLint")
Or put this in yourWORKSPACE:
WORKSPACE
load("@bazel_tools//tools/build_defs/repo:http.bzl","http_archive")http_archive(name="build_bazel_rules_apple",sha256="390841dd5f8a85fc25776684f4793d56e21b098dfd7243cd145b9831e6ef8be6",url="https://github.com/bazelbuild/rules_apple/releases/download/2.4.1/rules_apple.2.4.1.tar.gz",)load("@build_bazel_rules_apple//apple:repositories.bzl","apple_rules_dependencies",)apple_rules_dependencies()load("@build_bazel_rules_swift//swift:repositories.bzl","swift_rules_dependencies",)swift_rules_dependencies()load("@build_bazel_rules_swift//swift:extras.bzl","swift_rules_extra_dependencies",)swift_rules_extra_dependencies()http_archive(name="SwiftLint",sha256="c6ea58b9c72082cdc1ada4a2d48273ecc355896ed72204cedcc586b6ccb8aca6",url="https://github.com/realm/SwiftLint/releases/download/0.52.4/bazel.tar.gz",)load("@SwiftLint//bazel:repos.bzl","swiftlint_repos")swiftlint_repos()load("@SwiftLint//bazel:deps.bzl","swiftlint_deps")swiftlint_deps()
Then you can run SwiftLint in the current directory with this command:
bazel run -c opt @SwiftLint//:swiftlintTo 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 your Xcode project to get warnings and errors displayedin the issue navigator.
To do this select the project in the file navigator, then select the primary apptarget, and go to Build Phases. Click the + and select "New Run Script Phase".Insert the following as the script:
Xcode 15 made a significant change by setting the default value of theENABLE_USER_SCRIPT_SANDBOXING Build Setting fromNO toYES.As a result, SwiftLint encounters an error related to missing file permissions,which typically manifests as follows:error: Sandbox: swiftlint(19427) deny(1) file-read-data.
To resolve this issue, it is necessary to manually set theENABLE_USER_SCRIPT_SANDBOXING setting toNO for the specific target that SwiftLint is being configured for.
If you installed SwiftLint via Homebrew on Apple Silicon, you might experience this warning:
warning: SwiftLint not installed, download fromhttps://github.com/realm/SwiftLint
That is because Homebrew on Apple Silicon installs the binaries into the/opt/homebrew/binfolder by default. To instruct Xcode where to find SwiftLint, you can either add/opt/homebrew/bin to thePATH environment variable in your build phase
if [["$(uname -m)"== arm64 ]];thenexport PATH="/opt/homebrew/bin:$PATH"fiif which swiftlint> /dev/null;then swiftlintelseecho"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"fi
or you can create a symbolic link in/usr/local/bin pointing to the actual binary:
ln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlint
You might want to move your SwiftLint phase directly before the 'Compile Sources'step to detect errors quickly before compiling. However, SwiftLint is designedto run on valid Swift code that cleanly completes the compiler's parsing stage.So running SwiftLint before 'Compile Sources' might yield some incorrectresults.
If you wish to fix violations as well, your script could runswiftlint --fix && swiftlint instead of justswiftlint. This will meanthat all correctable violations are fixed while ensuring warnings show up inyour project for remaining violations.
If you've installed SwiftLint via CocoaPods the script should look like this:
"${PODS_ROOT}/SwiftLint/swiftlint"SwiftLint can be used as a build tool plugin for both Swift Package projectsand Xcode projects.
The build tool plugin determines the SwiftLint working directory by locatingthe topmost config file within the package/project directory. If a config fileis not found therein, the package/project directory is used as the workingdirectory.
The plugin throws an error when it is unable to resolve the SwiftLint workingdirectory. For example, this will occur in Xcode projects where the target'sSwift files are not located within the project directory.
To maximize compatibility with the plugin, avoid project structures that requirethe use of the--config option.
Project structures where SwiftLint's configuration file is locatedoutside of the package/project directory are not directly supportedby the build tool plugin. This is because it isn't possible to passarguments to build tool plugins (e.g., passing the config file path).
If your project structure doesn't work directly with the build toolplugin, please consider one of the following options:
- To use a config file located outside the package/project directory, a configfile may be added to that directory specifying a parent config path to theother config file, e.g.,
parent_config: path/to/.swiftlint.yml. - You can also consider the use of a Run Script Build Phase in place of thebuild tool plugin.
You can integrate SwiftLint as an Xcode Build Tool Plug-in if you're workingwith a project in Xcode.
Add SwiftLint as a package dependency to your project without linking any of theproducts.
Select the target you want to add linting to and open theBuild Phases inspector.OpenRun Build Tool Plug-ins and select the+ button.SelectSwiftLintPlugin from the list and add it to the project.
For unattended use (e.g. on CI), you can disable the package and macro validation dialog by
- individually passing
-skipPackagePluginValidationand-skipMacroValidationtoxcodebuildor - globally setting
defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YESanddefaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YESfor that user.
Note: This implicitly trusts all Xcode package plugins and macros in packages and bypasses Xcode's package validationdialogs, which has security implications.
You can integrate SwiftLint as a Swift Package Manager Plug-in if you're working witha Swift Package with aPackage.swift manifest.
Add SwiftLint as a package dependency to yourPackage.swift file.
Add SwiftLint to a target using theplugins parameter.
.target(... plugins:[.plugin(name:"SwiftLintPlugin",package:"SwiftLint")]),
To integrate SwiftLint withvscode, install thevscode-swiftlint extension from the marketplace.
You can use theofficial swiftlint fastlane action to run SwiftLint as part of your fastlane process.
swiftlint(mode::lint,# SwiftLint mode: :lint (default) or :autocorrectexecutable:"Pods/SwiftLint/swiftlint",# The SwiftLint binary path (optional). Important if you've installed it via CocoaPodspath:"/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)"AppDelegate.swift","path/to/project/Model.swift"],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))
swiftlint is also available as aDocker image usingUbuntu.So just the first time you need to pull the docker image using the next command:
docker pull ghcr.io/realm/swiftlint:latest
Then following times, you just runswiftlint inside of the docker like:
docker run -it -v`pwd`:`pwd` -w`pwd` ghcr.io/realm/swiftlint:latest
This will executeswiftlint in the folder where you are right now (pwd), showing an output like:
$ docker run -it -v`pwd`:`pwd` -w`pwd` ghcr.io/realm/swiftlint:latestLinting Swift filesin current working directoryLinting'RuleDocumentation.swift' (1/490)...Linting'YamlSwiftLintTests.swift' (490/490)Done linting! Found 0 violations, 0 seriousin 490 files.
Here you have more documentation about the usage ofDocker Images.
$ swiftlint helpOVERVIEW: A tool to enforce Swift style and conventions.USAGE: swiftlint <subcommand>OPTIONS: --version Show the version. -h, --help Show help information.SUBCOMMANDS: analyze Run analysis rules docs Open SwiftLint documentation website in the default web browser generate-docs Generates markdown documentation for all rules lint (default) Print lint warnings and errors reporters Display the list of reporters and their identifiers rules Display the list of rules and their identifiers version Display the current version of SwiftLint See 'swiftlint help <subcommand>' for detailed help.Runswiftlint in the directory containing the Swift files to lint. Directorieswill be searched recursively.
To specify a list of files when usinglint oranalyze(like the list of files modified by Xcode specified by theExtraBuildPhase Xcodeplugin, or modified files in the working tree based ongit ls-files -m), youcan do so by passing the option--use-script-input-files and setting thefollowing instance variables:SCRIPT_INPUT_FILE_COUNT andSCRIPT_INPUT_FILE_0,SCRIPT_INPUT_FILE_1...SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT - 1}.
These are same environment variables set for input files tocustom Xcode script phases.
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 Swiftcompiler, it just communicates with the official one you already have installedon your machine.
You should always run SwiftLint with the same toolchain you use to compile yourcode.
You may want to override SwiftLint's default Swift toolchain if you havemultiple toolchains or Xcodes installed.
Here's the order in which SwiftLint determines which Swift toolchain to use:
$XCODE_DEFAULT_TOOLCHAIN_OVERRIDE$TOOLCHAIN_DIRor$TOOLCHAINSxcrun -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 theusr/lib/ subdirectory ofthe value passed in the paths above.
You may also set theTOOLCHAINS environment variable to the reverse-DNSnotation that identifies a Swift toolchain version:
$ TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint --fix
On Linux, SourceKit is expected to be located in/usr/lib/libsourcekitdInProc.so or specified by theLINUX_SOURCEKIT_LIB_PATHenvironment variable.
SwiftLint can be run as apre-commit hook.Onceinstalled, add this to the.pre-commit-config.yaml in the root of your repository:
repos: -repo:https://github.com/realm/SwiftLintrev:0.50.3hooks: -id:swiftlint
Adjustrev to the SwiftLint version of your choice.pre-commit autoupdate can be used to update to the current version.
SwiftLint can be configured usingentry to apply fixes and fail on errors:
-repo:https://github.com/realm/SwiftLintrev:0.50.3hooks: -id:swiftlintentry:swiftlint --fix --strict
Over 200 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 themhere.
You can also checkSource/SwiftLintBuiltInRules/Rulesdirectory to see their implementation.
opt_in_rules are disabled by default (i.e., you have to explicitly enable themin 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)
Rules can be disabled with a comment inside a source file with the followingformat:
// swiftlint:disable <rule1> [<rule2> <rule3>...]
The rules will be disabled until the end of the file or until the linter sees amatching enable comment:
// swiftlint:enable <rule1> [<rule2> <rule3>...]
For example:
// swiftlint:disable colonletnoWarning:String="" // No warning about colons immediately after variable names!// swiftlint:enable colonlethasWarning:String="" // Warning generated about colons immediately after variable names
Including theall keyword will disable all rules until the linter sees a matching enable comment:
// swiftlint:disable all// swiftlint:enable all
For example:
// swiftlint:disable allletnoWarning:String="" // No warning about colons immediately after variable names!leti="" // Also no warning about short identifier names// swiftlint:enable alllethasWarning:String="" // Warning generated about colons immediately after variable nameslety="" // Warning generated about short identifier names
It's also possible to modify adisable orenable 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_castletnoWarning=NSNumber()as!IntlethasWarning=NSNumber()as!IntletnoWarning2=NSNumber()as!Int // swiftlint:disable:this force_castletnoWarning3=NSNumber()as!Int// swiftlint:disable:previous force_cast
Runswiftlint rules to print a list of all available rules and theiridentifiers.
Configure SwiftLint by adding a.swiftlint.yml file from the directory you'llrun SwiftLint from. The following parameters can be configured:
Rule inclusion:
disabled_rules: Disable rules from the default enabled set.opt_in_rules: Enable rules that are not part of the default set. Thespecialallidentifier will enable all opt in linter rules, except the oneslisted indisabled_rules.only_rules: Only the rules specified in this list will be enabled.Cannot be specified alongsidedisabled_rulesoropt_in_rules.analyzer_rules: This is an entirely separate list of rules that are onlyrun by theanalyzecommand. All analyzer rules are opt-in, so this is theonly configurable rule list, there are no equivalents fordisabled_rulesonly_rules.
# By default, SwiftLint uses a set of sensible default rules you can adjust:disabled_rules:# rule identifiers turned on by default to exclude from running -colon -comma -control_statementopt_in_rules:# some rules are turned off by default, so you need to opt-in -empty_count# find all the available rules by running: `swiftlint rules`# Alternatively, specify all rules explicitly by uncommenting this option:# only_rules: # delete `disabled_rules` & `opt_in_rules` if using this# - empty_parameters# - vertical_whitespaceanalyzer_rules:# rules run by `swiftlint analyze` -explicit_selfincluded:# case-sensitive paths to include during linting. `--path` is ignored if present -Sourcesexcluded:# case-sensitive paths to ignore during linting. Takes precedence over `included` -Carthage -Pods -Sources/ExcludedFolder -Sources/ExcludedFile.swift -Sources/*/ExcludedFile.swift# exclude files with a wildcard# If true, SwiftLint will not fail if no lintable files are found.allow_zero_lintable_files:false# If true, SwiftLint will treat all warnings as errors.strict:false# configurable rules can be customized from this configuration file# binary rules can set their severity levelforce_cast:warning# implicitlyforce_try:severity:warning# explicitly# rules that have both warning and error levels, can set just the warning level# implicitlyline_length:110# they can set both implicitly with an arraytype_body_length: -300# warning -400# error# or they can set both explicitlyfile_length:warning:500error:1200# naming rules can set warnings/errors for min_length and max_length# additionally they can set excluded namestype_name:min_length:4# only warningmax_length:# warning and errorwarning:40error:50excluded:iPhone# excluded via stringallowed_symbols:["_"]# these are allowed in type namesidentifier_name:min_length:# only min_lengtherror:4# only errorexcluded:# excluded via string array -id -URL -GlobalAPIKeyreporter:"xcode"# reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging, summary)
You can also use environment variables in your configuration file,by using${SOME_VARIABLE} in a string.
In addition to the rules that the main SwiftLint project ships with, SwiftLintcan also run two types of custom rules that you can define yourself in your ownprojects:
These rules are written the same way as the Swift-based rules that ship withSwiftLint so they're fast, accurate, can leverage SwiftSyntax, can be unittested, and more.
Using these requires building SwiftLint with Bazel as described inthis video or its associated code ingithub.com/jpsim/swiftlint-bazel-example.
You can define custom regex-based rules in your configuration file using thefollowing syntax:
custom_rules:pirates_beat_ninjas:# rule identifierincluded: -".*\\.swift"# regex that defines paths to include during linting. optional.excluded: -".*Test\\.swift"# regex that defines paths to exclude during linting. optionalname:"Pirates Beat Ninjas"# rule name. optional.regex:"([nN]inja)"# matching patterncapture_group:0# number of regex capture group to highlight the rule violation at. optional.match_kinds:# SyntaxKinds to match. optional. -comment -identifiermessage:"Pirates are better than ninjas."# violation message. optional.severity:error# violation severity. optional.no_hiding_in_strings:regex:"([nN]inja)"match_kinds:string
This is what the output would look like:
It is important to note that the regular expression pattern is used with the flagssandm enabled, that is.matches newlinesand^/$match the start and end of lines,respectively. If you do not want to have. match newlines, for example, the regex can be prepended by(?-s).
You can filter the matches by providing one or morematch_kinds, which willreject matches that include syntax kinds that are not present in this list. Hereare all the possible syntax kinds:
argumentattribute.builtinattribute.idbuildconfig.idbuildconfig.keywordcommentcomment.markcomment.urldoccommentdoccomment.fieldidentifierkeywordnumberobjectliteralparameterplaceholderstringstring_interpolation_anchortypeidentifier
All syntax kinds used in a snippet of Swift code can be extracted askingSourceKitten. For example,sourcekitten syntax --text "struct S {}" delivers
source.lang.swift.syntaxtype.keywordfor thestructkeyword andsource.lang.swift.syntaxtype.identifierfor its nameS
which match tokeyword andidentifier in the above list.
If using custom rules in combination withonly_rules, make sure to addcustom_rules as an item underonly_rules.
Unlike Swift custom rules, you can use official SwiftLint builds(e.g. from Homebrew) to run regex custom rules.
SwiftLint can automatically correct certain violations. Files on disk areoverwritten with a corrected version.
Please make sure to have backups of these files before runningswiftlint --fix, otherwise important data may be lost.
Standard linting is disabled while correcting because of the high likelihood ofviolations (or their offsets) being incorrect after modifying a file whileapplying corrections.
Theswiftlint analyze command can lint Swift files using thefull type-checked AST. The compiler log path containing the cleanswiftc buildcommand invocation (incremental builds will fail) must be passed toanalyzevia the--compiler-log-path flag.e.g.--compiler-log-path /path/to/xcodebuild.log
This can be obtained by
- Cleaning DerivedData (incremental builds won't work with analyze)
- Running
xcodebuild -workspace {WORKSPACE}.xcworkspace -scheme {SCHEME} > xcodebuild.log - Running
swiftlint analyze --compiler-log-path xcodebuild.log
Analyzer rules tend to be considerably slower than lint rules.
SwiftLint offers a variety of ways to include multiple configuration files.Multiple configuration files get merged into one single configuration that is then appliedjust as a single configuration file would get applied.
There are quite a lot of use cases where using multiple configuration files could be helpful:
For instance, one could use a team-wide shared SwiftLint configuration while allowing overridesin each project via a child configuration file.
Team-Wide Configuration:
disabled_rules:-force_cast
Project-Specific Configuration:
opt_in_rules:-force_cast
You can specify achild_config and / or aparent_config reference within a configuration file.These references should be local paths relative to the folder of the configuration file they are specified in.This even works recursively, as long as there are no cycles and no ambiguities.
A child config is treated as a refinement and therefore has a higher priority,while a parent config is considered a base with lower priority in case of conflicts.
Here's an example, assuming you have the following file structure:
ProjectRoot |_ .swiftlint.yml |_ .swiftlint_refinement.yml |_ Base |_ .swiftlint_base.ymlTo include both the refinement and the base file, your.swiftlint.yml should look like this:
child_config:.swiftlint_refinement.ymlparent_config:Base/.swiftlint_base.yml
When merging parent and child configs,included andexcluded configurationsare processed carefully to account for differences in the directory locationof the containing configuration files.
Just as you can provide localchild_config /parent_config references, instead ofreferencing local paths, you can just put urls that lead to configuration files.In order for SwiftLint to detect these remote references, they must start withhttp:// orhttps://.
The referenced remote configuration files may even recursively reference otherremote configuration files, but aren't allowed to include local references.
Using a remote reference, your.swiftlint.yml could look like this:
parent_config:https://myteamserver.com/our-base-swiftlint-config.yml
Every time you run SwiftLint and have an Internet connection, SwiftLint tries to get a new version ofevery remote configuration that is referenced. If this request times out, a cached version isused if available. If there is no cached version available, SwiftLint fails – but no worries, a cached versionshould be there once SwiftLint has run successfully at least once.
If needed, the timeouts for the remote configuration fetching can be specified manually via theconfiguration file(s) using theremote_timeout /remote_timeout_if_cached specifiers.These values default to 2 / 1 second(s).
Instead of just providing one configuration file when running SwiftLint via the command line,you can also pass a hierarchy, where the first configuration is treated as a parent,while the last one is treated as the highest-priority child.
A simple example including just two configuration files looks like this:
swiftlint --config .swiftlint.yml --config .swiftlint_child.yml
In addition to a main configuration (the.swiftlint.yml file in the root folder),you can put other configuration files named.swiftlint.yml into the directory structurethat then get merged as a child config, but only with an effect for those filesthat are within the same directory as the config or in a deeper directory wherethere isn't another configuration file. In other words: Nested configurations don't workrecursively – there's a maximum number of one nested configuration per filethat may be applied in addition to the main configuration.
.swiftlint.yml files are only considered as a nested configuration if they have not beenused to build the main configuration already (e. g. by having been referenced via somethinglikechild_config: Folder/.swiftlint.yml). Also,parent_config /child_configspecifications of nested configurations are getting ignored because there's no sense to that.
If one (or more) SwiftLint file(s) are explicitly specified via the--config parameter,that configuration will be treated as an override, no matter whether there existother.swiftlint.yml files somewhere within the directory.So if you want to usenested configurations, you can't use the--config parameter.
SwiftLint is maintained and funded by Realm Inc. The names and logos forRealm are trademarks of Realm Inc.
We ❤️ open source software!Seeour other open source projects,readour blog, or say hi on twitter(@realm).
Our thanks to MacStadium for providing a Mac Mini to run our performancetests.
About
A tool to enforce Swift style and conventions.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Languages
- Swift98.0%
- Starlark0.7%
- Ruby0.5%
- Makefile0.3%
- Shell0.2%
- HTML0.1%
- Other0.2%





