{"id":895,"url":"https://github.com/realm/SwiftLint","last_synced_at":"2025-08-06T14:31:19.184Z","repository":{"id":32159083,"uuid":"35732214","full_name":"realm/SwiftLint","owner":"realm","description":"A tool to enforce Swift style and conventions.","archived":false,"fork":false,"pushed_at":"2025-08-02T21:49:59.000Z","size":975303,"stargazers_count":19117,"open_issues_count":459,"forks_count":2263,"subscribers_count":245,"default_branch":"main","last_synced_at":"2025-08-04T05:37:35.339Z","etag":null,"topics":["code-quality","hacktoberfest","linter","linting","static-analysis","swift"],"latest_commit_sha":null,"homepage":"https://realm.github.io/SwiftLint","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/realm.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2015-05-16T16:59:31.000Z","updated_at":"2025-08-03T20:02:44.000Z","dependencies_parsed_at":"2023-10-03T01:01:25.623Z","dependency_job_id":"bbe8081d-7a0c-4688-b495-0e3a7e682051","html_url":"https://github.com/realm/SwiftLint","commit_stats":{"total_commits":5590,"total_committers":457,"mean_commits":"12.231947483588621","dds":0.6738819320214668,"last_synced_commit":"f410ea51a7ac242070f3e4e2a88dc2519ea9aabc"},"previous_names":[],"tags_count":139,"template":false,"template_full_name":null,"purl":"pkg:github/realm/SwiftLint","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/realm%2FSwiftLint","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/realm%2FSwiftLint/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/realm%2FSwiftLint/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/realm%2FSwiftLint/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/realm","download_url":"https://codeload.github.com/realm/SwiftLint/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/realm%2FSwiftLint/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":269093052,"owners_count":24358585,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-06T02:00:09.910Z","response_time":99,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["code-quality","hacktoberfest","linter","linting","static-analysis","swift"],"created_at":"2024-01-05T20:15:34.123Z","updated_at":"2025-08-06T14:31:19.140Z","avatar_url":"https://github.com/realm.png","language":"Swift","readme":"# SwiftLint\n\nA tool to enforce Swift style and conventions, loosely based on the now\narchived [GitHub Swift Style Guide](https://github.com/github/swift-style-guide).\nSwiftLint enforces the style guide rules that are generally accepted by the\nSwift community. These rules are well described in popular style guides like\n[Kodeco's Swift Style Guide](https://github.com/kodecocodes/swift-style-guide).\n\nSwiftLint hooks into [Clang](http://clang.llvm.org) and\n[SourceKit](http://www.jpsim.com/uncovering-sourcekit) to use the\n[AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) representation\nof your source files for more accurate results.\n\n[![Supported Swift Versions](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Frealm%2FSwiftLint%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/realm/SwiftLint)\n[![Supported Platforms](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Frealm%2FSwiftLint%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/realm/SwiftLint)\n[![Azure Build Status](https://dev.azure.com/jpsim/SwiftLint/_apis/build/status/realm.SwiftLint?branchName=main)](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=main)\n[![Buildkite Build Status](https://badge.buildkite.com/e2a5bc32c347e76e2793e4c5764a5f42bcd42bbe32f79c3a53.svg?branch=main)](https://buildkite.com/swiftlint/swiftlint)\n\n![SwiftLint violations highlighted in the Xcode editor](https://raw.githubusercontent.com/realm/SwiftLint/main/assets/screenshot.png)\n\nThis project adheres to the\n[Contributor Covenant Code of Conduct](https://realm.io/conduct).\nBy participating, you are expected to uphold this code.\n\n\u003e Switch Language:\n\u003e [中文](https://github.com/realm/SwiftLint/blob/main/README_CN.md)\n\u003e [한국어](https://github.com/realm/SwiftLint/blob/main/README_KR.md)\n\n## Video Introduction\n\nTo get a high-level overview of SwiftLint, we encourage you to watch this\npresentation recorded January 9th, 2017 by JP Simard (transcript provided):\n\n[![Presentation](https://raw.githubusercontent.com/realm/SwiftLint/main/assets/presentation.svg)](https://youtu.be/9Z1nTMTejqU)\n\n## Installation\n\n### [Swift Package Manager](https://github.com/apple/swift-package-manager)\n\nSwiftLint can be used as a [command plugin](#swift-package-command-plugin)\nor a [build tool plugin](#build-tool-plugins).\n\nAdd\n\n```swift\n.package(url: \"https://github.com/SimplyDanny/SwiftLintPlugins\", from: \"\u003cversion\u003e\")\n```\n\nto your `Package.swift` file to consume the latest release of SwiftLint\nautomatically or pin the dependency to a specific version:\n\n```swift\n.package(url: \"https://github.com/SimplyDanny/SwiftLintPlugins\", exact: \"\u003cversion\u003e\")\n```\n\nTherein, replace `\u003cversion\u003e` with the desired minimum or exact version.\n\n\u003e [!NOTE]\n\u003e Consuming the plugins directly from the SwiftLint repository comes\n\u003e with several drawbacks. To avoid them and reduce the overhead imposed, it's\n\u003e highly recommended to consume the plugins from the dedicated\n\u003e [SwiftLintPlugins repository](https://github.com/SimplyDanny/SwiftLintPlugins),\n\u003e even though plugins from the SwiftLint repository are also absolutely\n\u003e functional. If the plugins from SwiftLint are preferred, just use the URL\n\u003e `https://github.com/realm/SwiftLint` in the package declarations above.\n\u003e\n\u003e However, [SwiftLintPlugins](https://github.com/SimplyDanny/SwiftLintPlugins)\n\u003e facilitates plugin adoption massively. It lists some of the reasons that\n\u003e drive the plugins as provided by SwiftLint itself very troublesome. Since\n\u003e the plugin code and the releases are kept in sync, there is no difference\n\u003e in functionality between the two, but you spare yourself a lot of time and\n\u003e trouble using the dedicated plugins repository.\n\u003e\n\u003e This document assumes you're relying on SwiftLintPlugins.\n\n### [Xcode Package Dependency](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app)\n\nUse the following link to add SwiftLint as a Package Dependency to an Xcode\nproject:\n\n```bash\nhttps://github.com/SimplyDanny/SwiftLintPlugins\n```\n\n### [Homebrew](http://brew.sh)\n\n```bash\nbrew install swiftlint\n```\n\n### [CocoaPods](https://cocoapods.org)\n\nAdd the following to your `Podfile`:\n\n```ruby\npod 'SwiftLint'\n```\n\nThis will download the SwiftLint binaries and dependencies in `Pods/` during\nyour next `pod install` execution and will allow you to invoke it via\n`${PODS_ROOT}/SwiftLint/swiftlint` in your Script Build Phases.\n\nInstalling via Cocoapods also enables pinning to a specific version of\nSwiftLint rather than simply the latest (which is the case with\n[Homebrew](#homebrew)).\n\nNote that this will add the SwiftLint binaries, its dependencies' binaries, and\nthe Swift binary library distribution to the `Pods/` directory, so checking in\nthis directory to SCM such as Git is discouraged.\n\n### [Mint](https://github.com/yonaskolb/mint)\n\n```bash\nmint install realm/SwiftLint\n```\n\n### [Bazel](https://bazel.build)\n\nPut this in your `MODULE.bazel`:\n\n```bzl\nbazel_dep(name = \"swiftlint\", version = \"0.52.4\", repo_name = \"SwiftLint\")\n```\n\nOr put this in your `WORKSPACE`:\n\n\u003cdetails\u003e\n\n\u003csummary\u003eWORKSPACE\u003c/summary\u003e\n\n```bzl\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\nhttp_archive(\n    name = \"build_bazel_rules_apple\",\n    sha256 = \"390841dd5f8a85fc25776684f4793d56e21b098dfd7243cd145b9831e6ef8be6\",\n    url = \"https://github.com/bazelbuild/rules_apple/releases/download/2.4.1/rules_apple.2.4.1.tar.gz\",\n)\n\nload(\n    \"@build_bazel_rules_apple//apple:repositories.bzl\",\n    \"apple_rules_dependencies\",\n)\n\napple_rules_dependencies()\n\nload(\n    \"@build_bazel_rules_swift//swift:repositories.bzl\",\n    \"swift_rules_dependencies\",\n)\n\nswift_rules_dependencies()\n\nload(\n    \"@build_bazel_rules_swift//swift:extras.bzl\",\n    \"swift_rules_extra_dependencies\",\n)\n\nswift_rules_extra_dependencies()\n\nhttp_archive(\n    name = \"SwiftLint\",\n    sha256 = \"c6ea58b9c72082cdc1ada4a2d48273ecc355896ed72204cedcc586b6ccb8aca6\",\n    url = \"https://github.com/realm/SwiftLint/releases/download/0.52.4/bazel.tar.gz\",\n)\n\nload(\"@SwiftLint//bazel:repos.bzl\", \"swiftlint_repos\")\n\nswiftlint_repos()\n\nload(\"@SwiftLint//bazel:deps.bzl\", \"swiftlint_deps\")\n\nswiftlint_deps()\n```\n\n\u003c/details\u003e\n\nThen you can run SwiftLint in the current directory with this command:\n\n```console\nbazel run -c opt @SwiftLint//:swiftlint\n```\n\n### Pre-Built Package\n\nDownload `SwiftLint.pkg` from the\n[latest GitHub release](https://github.com/realm/SwiftLint/releases/latest) and\nrun it.\n\n### From Source\n\nMake sure the build tool [Bazel](https://bazel.build) and a\nrecent [Swift toolchain](https://www.swift.org/download/) are\ninstalled and all tools are discoverable in your `PATH`.\n\nTo build SwiftLint, clone this repository and run `make install`.\n\n## Setup\n\n\u003e [!IMPORTANT]\n\u003e While it may seem intuitive to run SwiftLint before compiling Swift source\n\u003e files to exit a build early when there are lint violations, it is important\n\u003e to understand that SwiftLint is designed to analyze valid source code that\n\u003e is compilable. Non-compiling code can very easily lead to unexpected and\n\u003e confusing results, especially when executing with `--fix`/`--autocorrect`\n\u003e command line arguments.\n\n### Build Tool Plugins\n\nSwiftLint can be used as a build tool plugin for both\n[Swift Package projects](#swift-package-projects)\nand [Xcode projects](#xcode-projects).\n\nThe build tool plugin determines the SwiftLint working directory by locating\nthe topmost config file within the package/project directory. If a config file\nis not found therein, the package/project directory is used as the working\ndirectory.\n\nThe plugin throws an error when it is unable to resolve the SwiftLint working\ndirectory. For example, this will occur in Xcode projects where the target's\nSwift files are not located within the project directory.\n\nTo maximize compatibility with the plugin, avoid project structures that require\nthe use of the `--config` option.\n\n### Swift Package Projects\n\n\u003e [!NOTE]\n\u003e Requires installing via [Swift Package Manager](#swift-package-manager).\n\nBuild tool plugins run when building each target. When a project has multiple\ntargets, the plugin must be added to the desired targets individually.\n\nTo do this, add the plugin to the target(s) to be linted as follows:\n\n```swift\n.target(\n    ...\n    plugins: [.plugin(name: \"SwiftLintBuildToolPlugin\", package: \"SwiftLintPlugins\")]\n),\n```\n\n### Swift Package Command Plugin\n\n\u003e [!NOTE]\n\u003e Requires installing via [Swift Package Manager](#swift-package-manager).\n\nThe command plugin enables running SwiftLint from the command line as follows:\n\n```shell\nswift package plugin swiftlint\n```\n\n### Xcode Projects\n\n\u003e [!NOTE]\n\u003e Requires installing via [Xcode Package Dependency](#xcode-package-dependency).\n\nBuild tool plugins run as a build phase of each target. When a project has\nmultiple targets, the plugin must be added to the desired targets individually.\n\nTo do this, add the `SwiftLintBuildToolPlugin` to the `Run Build Tool Plug-ins`\nphase of the `Build Phases` for the target(s) to be linted.\n\n\u003e [!TIP]\n\u003e When using the plugin for the first time, be sure to trust and enable\n\u003e it when prompted. If a macros build warning exists, select it to trust\n\u003e and enable the macros as well.\n\nFor unattended use (e.g. on CI), package plugin and macro\nvalidations can be disabled with either of the following:\n\n* Using `xcodebuild` options:\n\n  ```bash\n  -skipPackagePluginValidation\n  -skipMacroValidation\n  ```\n\n* Setting Xcode defaults:\n\n  ```bash\n  defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES\n  defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES\n  ```\n\n\u003e [!IMPORTANT]\n\u003e The unattended use options bypass Xcode's validation dialogs\n\u003e and implicitly trust all plugins and macros, which has security implications.\n\n#### Unexpected Xcode Project Structures\n\nProject structures where SwiftLint's configuration file is located\noutside of the package/project directory are not directly supported\nby the build tool plugin. This is because it isn't possible to pass\narguments to build tool plugins (e.g., passing the config file path).\n\nIf your project structure doesn't work directly with the build tool\nplugin, please consider one of the following options:\n\n* To use a config file located outside the package/project directory, a config\n  file may be added to that directory specifying a parent config path to the\n  other config file, e.g., `parent_config: path/to/.swiftlint.yml`.\n* You can also consider the use of a\n  [Run Script Build Phase](#xcode-run-script-build-phase) in place of the build\n  tool plugin.\n\n### Xcode Run Script Build Phase\n\n\u003e [!NOTE]\n\u003e Based upon the installation method used, the shell command syntax in the\n\u003e Run Script Build Phase may be different or additional configuration could\n\u003e be required. Refer to the [installation](#installation) instructions for\n\u003e more information.\n\nIf the build tool plugin does not work for your project setup or when\nadditional custom setup is required, SwiftLint can be added as a Run Script\nBuild Phase. This is useful when a project setup relies on the `--config`\nSwiftLint option; or to lint all targets together in a single `swiftlint`\ninvocation. File inclusions and exclusions can be configured in the\n[`.swiftlint.yml` configuration](#configuration).\n\nTo do this, add a custom script to a `Run Script` phase of the `Build Phases`\nof the primary app target, after the `Compile Sources` phase. Use the\nfollowing script implementation:\n\n```bash\nif command -v swiftlint \u003e/dev/null 2\u003e\u00261\nthen\n    swiftlint\nelse\n    echo \"warning: `swiftlint` command not found - See https://github.com/realm/SwiftLint#installation for installation instructions.\"\nfi\n```\n\nIf you're using the SwiftLintPlugin in a Swift package,\nyou may refer to the `swiftlint` executable in the\nfollowing way:\n\n```bash\nSWIFT_PACKAGE_DIR=\"${BUILD_DIR%Build/*}SourcePackages/artifacts\"\nSWIFTLINT_CMD=$(ls \"$SWIFT_PACKAGE_DIR\"/swiftlintplugins/SwiftLintBinary/SwiftLintBinary.artifactbundle/swiftlint-*-macos/bin/swiftlint | head -n 1)\n\nif test -f \"$SWIFTLINT_CMD\" 2\u003e\u00261\nthen\n    \"$SWIFTLINT_CMD\"\nelse\n    echo \"warning: `swiftlint` command not found - See https://github.com/realm/SwiftLint#installation for installation instructions.\"\nfi\n```\n\n\u003e [!NOTE]\n\u003e The `SWIFTLINT_CMD` path uses the default Xcode configuration and has been\n\u003e tested on Xcode 15/16. In case of another configuration (e.g. a custom\n\u003e Swift package path), please adapt the values accordingly.\n\u003c!-- markdownlint-disable MD028 --\u003e\n\u003e [!TIP]\n\u003e Uncheck `Based on dependency analysis` to run `swiftlint` on all incremental\n\u003e builds, suppressing the unspecified outputs warning.\n\n#### Consideration for Xcode 15.0\n\nXcode 15 made a significant change by setting the default value of the\n`ENABLE_USER_SCRIPT_SANDBOXING` build setting from `NO` to `YES`.\nAs a result, SwiftLint encounters an error related to missing file permissions,\nwhich typically manifests as\n`error: Sandbox: swiftlint(19427) deny(1) file-read-data.`\n\nTo resolve this issue, it is necessary to manually set the\n`ENABLE_USER_SCRIPT_SANDBOXING` setting to `NO` for the specific target that\nSwiftLint is being configured for.\n\n#### Consideration for Apple Silicon\n\nIf you installed SwiftLint via Homebrew on Apple Silicon, you might experience\nthis warning:\n\n```bash\nwarning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\n```\n\nThat is because Homebrew on Apple Silicon installs the binaries into the\n`/opt/homebrew/bin` folder by default. To instruct Xcode where to find\nSwiftLint, you can either add `/opt/homebrew/bin` to the `PATH` environment\nvariable in your build phase:\n\n```bash\nif [[ \"$(uname -m)\" == arm64 ]]\nthen\n    export PATH=\"/opt/homebrew/bin:$PATH\"\nfi\n\nif command -v swiftlint \u003e/dev/null 2\u003e\u00261\nthen\n    swiftlint\nelse\n    echo \"warning: `swiftlint` command not found - See https://github.com/realm/SwiftLint#installation for installation instructions.\"\nfi\n```\n\nor you can create a symbolic link in `/usr/local/bin` pointing to the actual\nbinary:\n\n```bash\nln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlint\n```\n\n#### Additional Considerations\n\nIf you wish to fix violations as well, your script could run\n`swiftlint --fix \u0026\u0026 swiftlint` instead of just `swiftlint`. This will mean\nthat all correctable violations are fixed while ensuring warnings show up in\nyour project for remaining violations.\n\nIf you've installed SwiftLint via CocoaPods the script should look like this:\n\n```bash\n\"${PODS_ROOT}/SwiftLint/swiftlint\"\n```\n\n### Visual Studio Code\n\nTo integrate SwiftLint with [Visual Studio Code](https://code.visualstudio.com), install the\n[`vscode-swiftlint`](https://marketplace.visualstudio.com/items?itemName=vknabel.vscode-swiftlint)\nextension from the marketplace.\n\n### Fastlane\n\nYou can use the official\n[`swiftlint` fastlane action](https://docs.fastlane.tools/actions/swiftlint)\nto run SwiftLint as part of your fastlane process.\n\n```ruby\nswiftlint(\n    mode: :lint,                            # SwiftLint mode: :lint (default) or :autocorrect\n    executable: \"Pods/SwiftLint/swiftlint\", # The SwiftLint binary path (optional). Important if you've installed it via CocoaPods\n    path: \"/path/to/lint\",                  # Specify path to lint (optional)\n    output_file: \"swiftlint.result.json\",   # The path of the output file (optional)\n    reporter: \"json\",                       # The custom reporter to use (optional)\n    config_file: \".swiftlint-ci.yml\",       # The path of the configuration file (optional)\n    files: [                                # List of files to process (optional)\n        \"AppDelegate.swift\",\n        \"path/to/project/Model.swift\"\n    ],\n    ignore_exit_status: true,               # Allow fastlane to continue even if SwiftLint returns a non-zero exit status (Default: false)\n    quiet: true,                            # Don't print status logs like 'Linting ' \u0026 'Done linting' (Default: false)\n    strict: true                            # Fail on warnings? (Default: false)\n)\n```\n\n### Docker\n\nSwiftLint is also available as a [Docker](https://www.docker.com/) image using\n`Ubuntu`. So just the first time you need to pull the docker image using the\nnext command:\n\n```bash\ndocker pull ghcr.io/realm/swiftlint:latest\n```\n\nThen following times, you just run `swiftlint` inside of the docker like:\n\n```bash\ndocker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latest\n```\n\nThis will execute `swiftlint` in the folder where you are right now (`pwd`),\nshowing an output like:\n\n```bash\n$ docker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latest\nLinting Swift files in current working directory\nLinting 'RuleDocumentation.swift' (1/490)\n...\nLinting 'YamlSwiftLintTests.swift' (490/490)\nDone linting! Found 0 violations, 0 serious in 490 files.\n```\n\nHere you have more documentation about the usage of\n[Docker Images](https://docs.docker.com/).\n\n## Command Line Usage\n\n```txt\n$ swiftlint help\nOVERVIEW: A tool to enforce Swift style and conventions.\n\nUSAGE: swiftlint \u003csubcommand\u003e\n\nOPTIONS:\n  --version               Show the version.\n  -h, --help              Show help information.\n\nSUBCOMMANDS:\n  analyze                 Run analysis rules\n  docs                    Open SwiftLint documentation website in the default web browser\n  generate-docs           Generates markdown documentation for selected group of rules\n  lint (default)          Print lint warnings and errors\n  baseline                Operations on existing baselines\n  reporters               Display the list of reporters and their identifiers\n  rules                   Display the list of rules and their identifiers\n  version                 Display the current version of SwiftLint\n\n  See 'swiftlint help \u003csubcommand\u003e' for detailed help.\n```\n\nRun `swiftlint` in the directory containing the Swift files to lint. Directories\nwill be searched recursively.\n\nTo specify a list of files when using `lint` or `analyze`\n(like the list of files modified by Xcode specified by the\n[`ExtraBuildPhase`](https://github.com/norio-nomura/ExtraBuildPhase) Xcode\nplugin, or modified files in the working tree based on `git ls-files -m`), you\ncan do so by passing the option `--use-script-input-files` and setting the\nfollowing instance variables: `SCRIPT_INPUT_FILE_COUNT`\nand `SCRIPT_INPUT_FILE_0`, `SCRIPT_INPUT_FILE_1`, ...,\n`SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT - 1}`.\nSimilarly, files can be read from file lists by passing\nthe option `--use-script-input-file-lists` and setting the\nfollowing instance variables: `SCRIPT_INPUT_FILE_LIST_COUNT`\nand `SCRIPT_INPUT_FILE_LIST_0`, `SCRIPT_INPUT_FILE_LIST_1`, ...,\n`SCRIPT_INPUT_FILE_LIST_{SCRIPT_INPUT_FILE_LIST_COUNT - 1}`.\n\nThese are same environment variables set for input files to\n[custom Xcode script phases](http://indiestack.com/2014/12/speeding-up-custom-script-phases/).\n\n## Working With Multiple Swift Versions\n\nSwiftLint hooks into SourceKit so it continues working even as Swift evolves!\n\nThis also keeps SwiftLint lean, as it doesn't need to ship with a full Swift\ncompiler, it just communicates with the official one you already have installed\non your machine.\n\nYou should always run SwiftLint with the same toolchain you use to compile your\ncode.\n\nYou may want to override SwiftLint's default Swift toolchain if you have\nmultiple toolchains or Xcodes installed.\n\nHere's the order in which SwiftLint determines which Swift toolchain to use:\n\n* `$XCODE_DEFAULT_TOOLCHAIN_OVERRIDE`\n* `$TOOLCHAIN_DIR` or `$TOOLCHAINS`\n* `xcrun -find swift`\n* `/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`\n* `/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`\n* `~/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`\n* `~/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`\n\n`sourcekitd.framework` is expected to be found in the `usr/lib/` subdirectory of\nthe value passed in the paths above.\n\nYou may also set the `TOOLCHAINS` environment variable to the reverse-DNS\nnotation that identifies a Swift toolchain version:\n\n```shell\nTOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint --fix\n```\n\nOn Linux, SourceKit is expected to be located in\n`/usr/lib/libsourcekitdInProc.so` or specified by the `LINUX_SOURCEKIT_LIB_PATH`\nenvironment variable.\n\n## Git `pre-commit` Hook\n\nSwiftLint can be run as a [pre-commit](https://pre-commit.com/) hook.\nOnce [installed](https://pre-commit.com/#install), add this to the\n`.pre-commit-config.yaml` in the root of your repository:\n\n```yaml\nrepos:\n  - repo: https://github.com/realm/SwiftLint\n    rev: 0.57.1\n    hooks:\n      - id: swiftlint\n```\n\nAdjust `rev` to the SwiftLint version of your choice.  `pre-commit autoupdate`\ncan be used to update to the current version.\n\nSwiftLint can be configured using `entry` to apply fixes and fail on errors:\n\n```yaml\n-   repo: https://github.com/realm/SwiftLint\n    rev: 0.57.1\n    hooks:\n    -   id: swiftlint\n        entry: swiftlint --fix --strict\n```\n\n## Rules\n\nOver 200 rules are included in SwiftLint and the Swift community (that's you!)\ncontinues to contribute more over time.\n[Pull requests](https://github.com/realm/SwiftLint/blob/main/CONTRIBUTING.md)\nare encouraged.\n\nYou can find an updated list of rules and more information about them in the\n[Rule Directory](https://realm.github.io/SwiftLint/rule-directory.html).\n\nYou can also check the\n[Source/SwiftLintBuiltInRules/Rules](https://github.com/realm/SwiftLint/tree/main/Source/SwiftLintBuiltInRules/Rules)\ndirectory to see their implementation.\n\n### Opt-In Rules\n\n`opt_in_rules` are disabled by default (i.e., you have to explicitly enable them\nin your configuration file).\n\nGuidelines on when to mark a rule as opt-in:\n\n* A rule that can have many false positives (e.g. `empty_count`)\n* A rule that is too slow\n* A rule that is not general consensus or is only useful in some cases\n  (e.g. `force_unwrapping`)\n\n### Disable rules in code\n\nRules can be disabled with a comment inside a source file with the following\nformat:\n\n`// swiftlint:disable \u003crule1\u003e [\u003crule2\u003e \u003crule3\u003e...]`\n\nThe rules will be disabled until the end of the file or until the linter sees a\nmatching enable comment:\n\n`// swiftlint:enable \u003crule1\u003e [\u003crule2\u003e \u003crule3\u003e...]`\n\nFor example:\n\n```swift\n// swiftlint:disable colon\nlet noWarning :String = \"\" // No warning about colons immediately after variable names!\n// swiftlint:enable colon\nlet hasWarning :String = \"\" // Warning generated about colons immediately after variable names\n```\n\nIncluding the `all` keyword will disable all rules until the linter sees a\nmatching enable comment:\n\n`// swiftlint:disable all`\n`// swiftlint:enable all`\n\nFor example:\n\n```swift\n// swiftlint:disable all\nlet noWarning :String = \"\" // No warning about colons immediately after variable names!\nlet i = \"\" // Also no warning about short identifier names\n// swiftlint:enable all\nlet hasWarning :String = \"\" // Warning generated about colons immediately after variable names\nlet y = \"\" // Warning generated about short identifier names\n```\n\nIt's also possible to modify a `disable` or `enable` command by appending\n`:previous`, `:this` or `:next` for only applying the command to the previous,\nthis (current) or next line respectively.\n\nFor example:\n\n```swift\n// swiftlint:disable:next force_cast\nlet noWarning = NSNumber() as! Int\nlet hasWarning = NSNumber() as! Int\nlet noWarning2 = NSNumber() as! Int // swiftlint:disable:this force_cast\nlet noWarning3 = NSNumber() as! Int\n// swiftlint:disable:previous force_cast\n```\n\nRun `swiftlint rules` to print a list of all available rules and their\nidentifiers.\n\n### Configuration\n\nConfigure SwiftLint by adding a `.swiftlint.yml` file from the directory you'll\nrun SwiftLint from. The following parameters can be configured:\n\nRule inclusion:\n\n* `disabled_rules`: Disable rules from the default enabled set.\n* `opt_in_rules`: Enable rules that are not part of the default set. The\n   special `all` identifier will enable all opt in linter rules, except the ones\n   listed in `disabled_rules`.\n* `only_rules`: Only the rules specified in this list will be enabled.\n   Cannot be specified alongside `disabled_rules` or `opt_in_rules`.\n* `analyzer_rules`: This is an entirely separate list of rules that are only\n  run by the `analyze` command. All analyzer rules are opt-in, so this is the\n  only configurable rule list, there are no equivalents for `disabled_rules`\n  and `only_rules`. The special `all` identifier can also be used here to enable\n  all analyzer rules, except the ones listed in `disabled_rules`.\n\n```yaml\n# By default, SwiftLint uses a set of sensible default rules you can adjust:\ndisabled_rules: # rule identifiers turned on by default to exclude from running\n  - colon\n  - comma\n  - control_statement\nopt_in_rules: # some rules are turned off by default, so you need to opt-in\n  - empty_count # find all the available rules by running: `swiftlint rules`\n\n# Alternatively, specify all rules explicitly by uncommenting this option:\n# only_rules: # delete `disabled_rules` \u0026 `opt_in_rules` if using this\n#   - empty_parameters\n#   - vertical_whitespace\n\nanalyzer_rules: # rules run by `swiftlint analyze`\n  - explicit_self\n\n# Case-sensitive paths to include during linting. Directory paths supplied on the\n# command line will be ignored.\nincluded: \n  - Sources\nexcluded: # case-sensitive paths to ignore during linting. Takes precedence over `included`\n  - Carthage\n  - Pods\n  - Sources/ExcludedFolder\n  - Sources/ExcludedFile.swift\n  - Sources/*/ExcludedFile.swift # exclude files with a wildcard\n\n# If true, SwiftLint will not fail if no lintable files are found.\nallow_zero_lintable_files: false\n\n# If true, SwiftLint will treat all warnings as errors.\nstrict: false\n\n# If true, SwiftLint will treat all errors as warnings.\nlenient: false\n\n# The path to a baseline file, which will be used to filter out detected violations.\nbaseline: Baseline.json\n\n# The path to save detected violations to as a new baseline.\nwrite_baseline: Baseline.json\n\n# If true, SwiftLint will check for updates after linting or analyzing.\ncheck_for_updates: true\n\n# configurable rules can be customized from this configuration file\n# binary rules can set their severity level\nforce_cast: warning # implicitly\nforce_try:\n  severity: warning # explicitly\n# rules that have both warning and error levels, can set just the warning level\n# implicitly\nline_length: 110\n# they can set both implicitly with an array\ntype_body_length:\n  - 300 # warning\n  - 400 # error\n# or they can set both explicitly\nfile_length:\n  warning: 500\n  error: 1200\n# naming rules can set warnings/errors for min_length and max_length\n# additionally they can set excluded names\ntype_name:\n  min_length: 4 # only warning\n  max_length: # warning and error\n    warning: 40\n    error: 50\n  excluded: iPhone # excluded via string\n  allowed_symbols: [\"_\"] # these are allowed in type names\nidentifier_name:\n  min_length: # only min_length\n    error: 4 # only error\n  excluded: # excluded via string array\n    - id\n    - URL\n    - GlobalAPIKey\nreporter: \"xcode\" # reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging, summary)\n```\n\nYou can also use environment variables in your configuration file,\nby using `${SOME_VARIABLE}` in a string.\n\n### Defining Custom Rules\n\nIn addition to the rules that the main SwiftLint project ships with, SwiftLint\ncan also run two types of custom rules that you can define yourself in your own\nprojects:\n\n#### 1. Swift Custom Rules\n\nThese rules are written the same way as the Swift-based rules that ship with\nSwiftLint so they're fast, accurate, can leverage SwiftSyntax, can be unit\ntested, and more.\n\nUsing these requires building SwiftLint with Bazel as described in\n[this video](https://vimeo.com/820572803) or its associated code in\n[github.com/jpsim/swiftlint-bazel-example](https://github.com/jpsim/swiftlint-bazel-example).\n\n#### 2. Regex Custom Rules\n\nYou can define custom regex-based rules in your configuration file using the\nfollowing syntax:\n\n```yaml\ncustom_rules:\n  pirates_beat_ninjas: # rule identifier\n    included:\n      - \".*\\\\.swift\" # regex that defines paths to include during linting. optional.\n    excluded:\n      - \".*Test\\\\.swift\" # regex that defines paths to exclude during linting. optional\n    name: \"Pirates Beat Ninjas\" # rule name. optional.\n    regex: \"([nN]inja)\" # matching pattern\n    capture_group: 0 # number of regex capture group to highlight the rule violation at. optional.\n    match_kinds: # SyntaxKinds to match. optional.\n      - comment\n      - identifier\n    message: \"Pirates are better than ninjas.\" # violation message. optional.\n    severity: error # violation severity. optional.\n  no_hiding_in_strings:\n    regex: \"([nN]inja)\"\n    match_kinds: string\n```\n\nThis is what the output would look like:\n\n![Custom violations highlighted in the Xcode editor](https://raw.githubusercontent.com/realm/SwiftLint/main/assets/custom-rule.png)\n\nIt is important to note that the regular expression pattern is used with the\nflags `s` and `m` enabled, that is `.`\n[matches newlines](https://developer.apple.com/documentation/foundation/nsregularexpression/options/1412529-dotmatcheslineseparators)\nand `^`/`$`\n[match the start and end of lines](https://developer.apple.com/documentation/foundation/nsregularexpression/options/1408263-anchorsmatchlines),\nrespectively. If you do not want to have `.` match newlines, for example, the\nregex can be prepended by `(?-s)`.\n\nYou can filter the matches by providing one or more `match_kinds`, which will\nreject matches that include syntax kinds that are not present in this list. Here\nare all the possible syntax kinds:\n\n* `argument`\n* `attribute.builtin`\n* `attribute.id`\n* `buildconfig.id`\n* `buildconfig.keyword`\n* `comment`\n* `comment.mark`\n* `comment.url`\n* `doccomment`\n* `doccomment.field`\n* `identifier`\n* `keyword`\n* `number`\n* `objectliteral`\n* `parameter`\n* `placeholder`\n* `string`\n* `string_interpolation_anchor`\n* `typeidentifier`\n\nAll syntax kinds used in a snippet of Swift code can be extracted asking\n[SourceKitten](https://github.com/jpsim/SourceKitten). For example,\n`sourcekitten syntax --text \"struct S {}\"` delivers\n\n* `source.lang.swift.syntaxtype.keyword` for the `struct` keyword and\n* `source.lang.swift.syntaxtype.identifier` for its name `S`\n\nwhich match to `keyword` and `identifier` in the above list.\n\nIf using custom rules in combination with `only_rules`, you must include the\nliteral string `custom_rules` in the `only_rules` list:\n\n```yaml\nonly_rules:\n  - custom_rules\n\ncustom_rules:\n  no_hiding_in_strings:\n    regex: \"([nN]inja)\"\n    match_kinds: string\n```\n\nUnlike Swift custom rules, you can use official SwiftLint builds\n(e.g. from Homebrew) to run regex custom rules.\n\n### Auto-correct\n\nSwiftLint can automatically correct certain violations. Files on disk are\noverwritten with a corrected version.\n\nPlease make sure to have backups of these files before running\n`swiftlint --fix`, otherwise important data may be lost.\n\nStandard linting is disabled while correcting because of the high likelihood of\nviolations (or their offsets) being incorrect after modifying a file while\napplying corrections.\n\n### Analyze\n\nThe `swiftlint analyze` command can lint Swift files using the\nfull type-checked AST. The compiler log path containing the clean `swiftc` build\ncommand invocation (incremental builds will fail) must be passed to `analyze`\nvia the `--compiler-log-path` flag.\ne.g. `--compiler-log-path /path/to/xcodebuild.log`\n\nThis can be obtained by\n\n1. Cleaning DerivedData (incremental builds won't work with analyze)\n2. Running `xcodebuild -workspace {WORKSPACE}.xcworkspace -scheme {SCHEME} \u003e xcodebuild.log`\n3. Running `swiftlint analyze --compiler-log-path xcodebuild.log`\n\nAnalyzer rules tend to be considerably slower than lint rules.\n\n## Using Multiple Configuration Files\n\nSwiftLint offers a variety of ways to include multiple configuration files.\nMultiple configuration files get merged into one single configuration that is\nthen applied just as a single configuration file would get applied.\n\nThere are quite a lot of use cases where using multiple configuration files\ncould be helpful:\n\nFor instance, one could use a team-wide shared SwiftLint configuration while\nallowing overrides in each project via a child configuration file.\n\nTeam-Wide Configuration:\n\n```yaml\ndisabled_rules:\n- force_cast\n```\n\nProject-Specific Configuration:\n\n```yaml\nopt_in_rules:\n- force_cast\n```\n\n### Child/Parent Configs (Locally)\n\nYou can specify a `child_config` and/or a `parent_config` reference within a\nconfiguration file. These references should be local paths relative to the\nfolder of the configuration file they are specified in. This even works\nrecursively, as long as there are no cycles and no ambiguities.\n\n**A child config is treated as a refinement and thus has a higher priority**,\nwhile a parent config is considered a base with lower priority in case of\nconflicts.\n\nHere's an example, assuming you have the following file structure:\n\n```txt\nProjectRoot\n    |_ .swiftlint.yml\n    |_ .swiftlint_refinement.yml\n    |_ Base\n        |_ .swiftlint_base.yml\n```\n\nTo include both the refinement and the base file, your `.swiftlint.yml` should\nlook like this:\n\n```yaml\nchild_config: .swiftlint_refinement.yml\nparent_config: Base/.swiftlint_base.yml\n```\n\nWhen merging parent and child configs, `included` and `excluded` configurations\nare processed carefully to account for differences in the directory location\nof the containing configuration files.\n\n### Child/Parent Configs (Remote)\n\nJust as you can provide local `child_config`/`parent_config` references,\ninstead of referencing local paths, you can just put urls that lead to\nconfiguration files. In order for SwiftLint to detect these remote references,\nthey must start with `http://` or `https://`.\n\nThe referenced remote configuration files may even recursively reference other\nremote configuration files, but aren't allowed to include local references.\n\nUsing a remote reference, your `.swiftlint.yml` could look like this:\n\n```yaml\nparent_config: https://myteamserver.com/our-base-swiftlint-config.yml\n```\n\nEvery time you run SwiftLint and have an Internet connection, SwiftLint tries\nto get a new version of every remote configuration that is referenced. If this\nrequest times out, a cached version is used if available. If there is no cached\nversion available, SwiftLint fails – but no worries, a cached version should be\nthere once SwiftLint has run successfully at least once.\n\nIf needed, the timeouts for the remote configuration fetching can be specified\nmanually via the configuration file(s) using the\n`remote_timeout`/`remote_timeout_if_cached` specifiers. These values default\nto 2 seconds or 1 second, respectively.\n\n### Command Line\n\nInstead of just providing one configuration file when running SwiftLint via the\ncommand line, you can also pass a hierarchy, where the first configuration is\ntreated as a parent, while the last one is treated as the highest-priority\nchild.\n\nA simple example including just two configuration files looks like this:\n\n`swiftlint --config .swiftlint.yml --config .swiftlint_child.yml`\n\n### Nested Configurations\n\nIn addition to a main configuration (the `.swiftlint.yml` file in the root\nfolder), you can put other configuration files named `.swiftlint.yml` into the\ndirectory structure that then get merged as a child config, but only with an\neffect for those files that are within the same directory as the config or in a\ndeeper directory where there isn't another configuration file. In other words:\nNested configurations don't work recursively – there's a maximum number of one\nnested configuration per file that may be applied in addition to the main\nconfiguration.\n\n`.swiftlint.yml` files are only considered as a nested configuration if they\nhave not been used to build the main configuration already (e. g. by having\nbeen referenced via something like `child_config: Folder/.swiftlint.yml`).\nAlso, `parent_config`/`child_config` specifications of nested configurations\nare getting ignored because there's no sense to that.\n\nIf one (or more) SwiftLint file(s) are explicitly specified via the `--config`\nparameter, that configuration will be treated as an override, no matter whether\nthere exist other `.swiftlint.yml` files somewhere within the directory.\n**So if you want to use nested configurations, you can't use the `--config`\nparameter.**\n\n## License\n\n[MIT licensed.](https://github.com/realm/SwiftLint/blob/main/LICENSE)\n\n## About\n\nSwiftLint is utterly maintained by volunteers contributing to its success\nentirely in their free time. As such, SwiftLint isn't a commercial product\nin any way.\n\nBe kind to the people maintaining SwiftLint as a hobby and accept that their\ntime is limited. Support them by contributing to the project, reporting issues,\nand helping others in the community.\n\nSpecial thanks go to [MacStadium](https://www.macstadium.com) for providing\nphysical Mac mini machines to run our performance tests.\n\n![MacStadium](https://raw.githubusercontent.com/realm/SwiftLint/main/assets/macstadium.png)\n\nWe also thank Realm (now MongoDB) for their inital contributions and setup of\nthe project.\n","funding_links":[],"categories":["Code Quality","Libs","Swift","Linters","Swiftlint ##","Coding convention","\u003ca id=\"dev_tools\"\u003e\u003c/a\u003e1#开发工具","Guide","The Index","技术方向","HarmonyOS","Development","\u003ca name=\"for-projects\"\u003e\u003c/a\u003e For Projects","Quality [🔝](#readme)","前端开发框架及项目","OOM-Leaks-Crash","Tools","Frameworks with plugins","Command Line Utilities","Cross-Platform Mobile Guide for Native iOS \u0026 Android Developers","Linter"],"sub_categories":["Linter","Quality","Swift","Swift Lint","\u003ca name=\"swift-tools\"\u003e\u003c/a\u003eSwift Tools","3. Xcode 插件","Other free courses","Swift Style Guide","Developer Tools","iOS","Windows Manager","Time Series","\u003ca name=\"for-projects-example-projects\"\u003e\u003c/a\u003e Example Projects","其他_文本生成、文本对话","Tools"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frealm%2FSwiftLint","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frealm%2FSwiftLint","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frealm%2FSwiftLint/lists"}