## 1. Project Overview & Quickstart (realm/SwiftLint)

## File: README.md

# SwiftLint

A tool to enforce Swift style and conventions, loosely based on the now
archived [GitHub Swift Style Guide](https://github.com/github/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 like
[Kodeco's Swift Style Guide](https://github.com/kodecocodes/swift-style-guide).

SwiftLint rules are predominantly based on [SwiftSyntax](https://github.com/swiftlang/swift-syntax).
Some rules still hook into [Clang](http://clang.llvm.org) and
[SourceKit](http://www.jpsim.com/uncovering-sourcekit) to access type information.

[](https://swiftpackageindex.com/realm/SwiftLint)
[](https://swiftpackageindex.com/realm/SwiftLint)
[](https://buildkite.com/swiftlint/swiftlint)



This project adheres to the
[Contributor Covenant Code of Conduct](https://realm.io/conduct).
By participating, you are expected to uphold this code.

> Switch Language:
> [中文](https://github.com/realm/SwiftLint/blob/main/README_CN.md),
> [한국어](https://github.com/realm/SwiftLint/blob/main/README_KR.md)

## Video Introduction

To get a high-level overview of SwiftLint, we encourage you to watch this
presentation recorded January 9th, 2017 by JP Simard (transcript provided):

[](https://youtu.be/9Z1nTMTejqU)

## Installation

### [Swift Package Manager](https://github.com/apple/swift-package-manager)

SwiftLint can be used as a [command plugin](#swift-package-command-plugin)
or a [build tool plugin](#build-tool-plugins).

Add

```swift
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "<version>")
```

to your `Package.swift` file to consume the latest release of SwiftLint
automatically or pin the dependency to a specific version:

```swift
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", exact: "<version>")
```

Therein, replace `<version>` with the desired minimum or exact version.

> [!NOTE]
> Consuming the plugins directly from the SwiftLint repository comes
> with several drawbacks. To avoid them and reduce the overhead imposed, it's
> highly recommended to consume the plugins from the dedicated
> [SwiftLintPlugins repository](https://github.com/SimplyDanny/SwiftLintPlugins),
> even though plugins from the SwiftLint repository are also absolutely
> functional. If the plugins from SwiftLint are preferred, just use the URL
> `https://github.com/realm/SwiftLint` in the package declarations above.
>
> However, [SwiftLintPlugins](https://github.com/SimplyDanny/SwiftLintPlugins)
> facilitates plugin adoption massively. It lists some of the reasons that
> drive the plugins as provided by SwiftLint itself very troublesome. Since
> the plugin code and the releases are kept in sync, there is no difference
> in functionality between the two, but you spare yourself a lot of time and
> trouble using the dedicated plugins repository.
>
> This document assumes you're relying on SwiftLintPlugins.

### [Xcode Package Dependency](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app)

Use the following link to add SwiftLint as a Package Dependency to an Xcode
project:

```bash
https://github.com/SimplyDanny/SwiftLintPlugins
```

### [Homebrew](http://brew.sh)

```bash
brew install swiftlint
```

### [CocoaPods](https://cocoapods.org)

Add the following to your `Podfile`:

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

Installing via Cocoapods also enables pinning to a specific version of
SwiftLint rather than simply the latest (which is the case with
[Homebrew](#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.

### [Mint](https://github.com/yonaskolb/mint)

```bash
mint install realm/SwiftLint
```

### [Bazel](https://bazel.build)

Put this in your `MODULE.bazel`:

```bzl
bazel_dep(name = "swiftlint", version = "0.52.4", repo_name = "SwiftLint")
```

Or put this in your `WORKSPACE`:



WORKSPACE

```bzl
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:

```console
bazel run -c opt @SwiftLint//:swiftlint
```

### Pre-Built Package

Download `SwiftLint.pkg` from the
[latest GitHub release](https://github.com/realm/SwiftLint/releases/latest) and
run it.

### From Source

Make sure the build tool [Bazel](https://bazel.build) and a
recent [Swift toolchain](https://www.swift.org/download/) are
installed and all tools are discoverable in your `PATH`.

To build SwiftLint, clone this repository and run `make install`.

## Setup

> [!IMPORTANT]
> While it may seem intuitive to run SwiftLint before compiling Swift source
> files to exit a build early when there are lint violations, it is important
> to understand that SwiftLint is designed to analyze valid source code that
> is compilable. Non-compiling code can very easily lead to unexpected and
> confusing results, especially when executing with `--fix`/`--autocorrect`
> command line arguments.

### Build Tool Plugins

SwiftLint can be used as a build tool plugin for both
[Swift Package projects](#swift-package-projects)
and [Xcode projects](#xcode-projects).

The build tool plugin determines the SwiftLint working directory by locating
the topmost config file within the package/project directory. If a config file
is not found therein, the package/project directory is used as the working
directory.

The plugin throws an error when it is unable to resolve the SwiftLint working
directory. For example, this will occur in Xcode projects where the target's
Swift files are not located within the project directory.

To maximize compatibility with the plugin, avoid project structures that require
the use of the `--config` option.

### Swift Package Projects

> [!NOTE]
> Requires installing via [Swift Package Manager](#swift-package-manager).

Build tool plugins run when building each target. When a project has multiple
targets, the plugin must be added to the desired targets individually.

To do this, add the plugin to the target(s) to be linted as follows:

```swift
.target(
    ...
    plugins: [.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLintPlugins")]
),
```

### Swift Package Command Plugin

> [!NOTE]
> Requires installing via [Swift Package Manager](#swift-package-manager).

The command plugin enables running SwiftLint from the command line as follows:

```shell
swift package plugin swiftlint
```

### Xcode Projects

> [!NOTE]
> Requires installing via [Xcode Package Dependency](#xcode-package-dependency).

Build tool plugins run as a build phase of each target. When a project has
multiple targets, the plugin must be added to the desired targets individually.

To do this, add the `SwiftLintBuildToolPlugin` to the `Run Build Tool Plug-ins`
phase of the `Build Phases` for the target(s) to be linted.

> [!TIP]
> When using the plugin for the first time, be sure to trust and enable
> it when prompted. If a macros build warning exists, select it to trust
> and enable the macros as well.

For unattended use (e.g. on CI), package plugin and macro
validations can be disabled with either of the following:

* Using `xcodebuild` options:

  ```bash
  -skipPackagePluginValidation
  -skipMacroValidation
  ```

* Setting Xcode defaults:

  ```bash
  defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES
  defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES
  ```

> [!IMPORTANT]
> The unattended use options bypass Xcode's validation dialogs
> and implicitly trust all plugins and macros, which has security implications.

#### Unexpected Xcode Project Structures

Project structures where SwiftLint's configuration file is located
outside of the package/project directory are not directly supported
by the build tool plugin. This is because it isn't possible to pass
arguments to build tool plugins (e.g., passing the config file path).

If your project structure doesn't work directly with the build tool
plugin, please consider one of the following options:

* To use a config file located outside the package/project directory, a config
  file may be added to that directory specifying a parent config path to the
  other config file, e.g., `parent_config: path/to/.swiftlint.yml`.
* You can also consider the use of a
  [Run Script Build Phase](#xcode-run-script-build-phase) in place of the build
  tool plugin.

### Xcode Run Script Build Phase

> [!NOTE]
> Based upon the installation method used, the shell command syntax in the
> Run Script Build Phase may be different or additional configuration could
> be required. Refer to the [installation](#installation) instructions for
> more information.

If the build tool plugin does not work for your project setup or when
additional custom setup is required, SwiftLint can be added as a Run Script
Build Phase. This is useful when a project setup relies on the `--config`
SwiftLint option; or to lint all targets together in a single `swiftlint`
invocation. File inclusions and exclusions can be configured in the
[`.swiftlint.yml` configuration](#configuration).

To do this, add a custom script to a `Run Script` phase of the `Build Phases`
of the primary app target, after the `Compile Sources` phase. Use the
following script implementation:

```bash
if command -v swiftlint >/dev/null 2>&1
then
    swiftlint
else
    echo "warning: `swiftlint` command not found - See https://github.com/realm/SwiftLint#installation for installation instructions."
fi
```

If you're using the SwiftLintPlugin in a Swift package,
you may refer to the `swiftlint` executable in the
following way:

```bash
SWIFT_PACKAGE_DIR="${SWIFT_PACKAGE_DIR:-${BUILD_DIR%Build/*}SourcePackages}"
SWIFTLINT_CMD="$SWIFT_PACKAGE_DIR/artifacts/swiftlintplugins/SwiftLintBinary/SwiftLintBinary.artifactbundle/macos/swiftlint"

if test -f "$SWIFTLINT_CMD" 2>&1
then
    "$SWIFTLINT_CMD"
else
    echo "warning: `swiftlint` command not found - See https://github.com/realm/SwiftLint#xcode-run-script-build-phase for installation instructions."
fi
```

> [!NOTE]
> The `SWIFTLINT_CMD` path uses the default Xcode configuration and has been
> tested on Xcode 15/16. In case of another configuration (e.g. a custom
> Swift package path), please adapt the values accordingly.
> If you run `xcodebuild` with `-clonedSourcePackagesDirPath`, set
> `SWIFT_PACKAGE_DIR` to `` before running the script.

> [!TIP]
> Uncheck `Based on dependency analysis` to run `swiftlint` on all incremental
> builds, suppressing the unspecified outputs warning.

#### Consideration for Xcode 15.0

Xcode 15 made a significant change by setting the default value of the
`ENABLE_USER_SCRIPT_SANDBOXING` build setting from `NO` to `YES`.
As a result, SwiftLint encounters an error related to missing file permissions,
which typically manifests as
`error: Sandbox: swiftlint(19427) deny(1) file-read-data.`

To resolve this issue, it is necessary to manually set the
`ENABLE_USER_SCRIPT_SANDBOXING` setting to `NO` for the specific target that
SwiftLint is being configured for.

#### Consideration for Apple Silicon

If you installed SwiftLint via Homebrew on Apple Silicon, you might experience
this warning:

```bash
warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint
```

That is because Homebrew on Apple Silicon installs the binaries into the
`/opt/homebrew/bin` folder by default. To instruct Xcode where to find
SwiftLint, you can either add `/opt/homebrew/bin` to the `PATH` environment
variable in your build phase:

```bash
if [[ "$(uname -m)" == arm64 ]]
then
    export PATH="/opt/homebrew/bin:$PATH"
fi

if command -v swiftlint >/dev/null 2>&1
then
    swiftlint
else
    echo "warning: `swiftlint` command not found - See https://github.com/realm/SwiftLint#installation for installation instructions."
fi
```

or you can create a symbolic link in `/usr/local/bin` pointing to the actual
binary:

```bash
ln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlint
```

#### Additional Considerations

If you wish to fix violations as well, your script could run
`swiftlint --fix && swiftlint` instead of just `swiftlint`. This will mean
that all correctable violations are fixed while ensuring warnings show up in
your project for remaining violations.

If you've installed SwiftLint via CocoaPods the script should look like this:

```bash
"${PODS_ROOT}/SwiftLint/swiftlint"
```

### Visual Studio Code

To integrate SwiftLint with [Visual Studio Code](https://code.visualstudio.com), install the
[`vscode-swiftlint`](https://marketplace.visualstudio.com/items?itemName=vknabel.vscode-swiftlint)
extension from the marketplace.

### Fastlane

You can use the official
[`swiftlint` fastlane action](https://docs.fastlane.tools/actions/swiftlint)
to run SwiftLint as part of your fastlane process.

```ruby
swiftlint(
    mode: :lint,                            # SwiftLint mode: :lint (default) or :autocorrect
    executable: "Pods/SwiftLint/swiftlint", # The SwiftLint binary path (optional). Important if you've installed it via CocoaPods
    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)
        "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)
)
```

### Docker

SwiftLint is also available as a [Docker](https://www.docker.com/) image using
`Ubuntu`. So just the first time you need to pull the docker image using the
next command:

```bash
docker pull ghcr.io/realm/swiftlint:latest
```

Then following times, you just run `swiftlint` inside of the docker like:

```bash
docker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latest
```

This will execute `swiftlint` in the folder where you are right now (`pwd`),
showing an output like:

```bash
$ docker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latest
Linting Swift files in current working directory
Linting 'RuleDocumentation.swift' (1/490)
...
Linting 'YamlSwiftLintTests.swift' (490/490)
Done linting! Found 0 violations, 0 serious in 490 files.
```

Here you have more documentation about the usage of
[Docker Images](https://docs.docker.com/).

### MegaLinter

SwiftLint is also embedded in [MegaLinter](https://megalinter.io), an
open-source aggregator of linters for CI. See its
[SwiftLint documentation](https://megalinter.io/latest/descriptors/swift_swiftlint/)
for setup instructions.

## Command Line Usage

```txt
$ swiftlint help
OVERVIEW: 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 selected group of rules
  lint (default)          Print lint warnings and errors
  baseline                Operations on existing baselines
  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.
```

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

To specify a list of files when using `lint` or `analyze`
(like the list of files modified by Xcode specified by the
[`ExtraBuildPhase`](https://github.com/norio-nomura/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 - 1}`.
Similarly, files can be read from file lists by passing
the option `--use-script-input-file-lists` and setting the
following instance variables: `SCRIPT_INPUT_FILE_LIST_COUNT`
and `SCRIPT_INPUT_FILE_LIST_0`, `SCRIPT_INPUT_FILE_LIST_1`, ...,
`SCRIPT_INPUT_FILE_LIST_{SCRIPT_INPUT_FILE_LIST_COUNT - 1}`.

These are same environment variables set for input files to
[custom Xcode script phases](http://indiestack.com/2014/12/speeding-up-custom-script-phases/).

## Working With Multiple Swift Versions

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

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

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

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

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

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

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

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

```shell
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 the `LINUX_SOURCEKIT_LIB_PATH`
environment variable.

## Git `pre-commit` Hook

SwiftLint can be run as a [pre-commit](https://pre-commit.com/) hook.
Once [installed](https://pre-commit.com/#install), add this to the
`.pre-commit-config.yaml` in the root of your repository:

```yaml
repos:
  - repo: https://github.com/realm/SwiftLint
    rev: 0.57.1
    hooks:
      - id: swiftlint
```

Adjust `rev` to the SwiftLint version of your choice.  `pre-commit autoupdate`
can be used to update to the current version.

SwiftLint can be configured using `entry` to apply fixes and fail on errors:

```yaml
- repo: https://github.com/realm/SwiftLint
  rev: 0.57.1
  hooks:
    - id: swiftlint
      entry: swiftlint --fix --strict
```

## Rules

Over 200 rules are included in SwiftLint and the Swift community (that's you!)
continues to contribute more over time.
[Pull requests](https://github.com/realm/SwiftLint/blob/main/CONTRIBUTING.md)
are encouraged.

You can find an updated list of rules and more information about them in the
[Rule Directory](https://realm.github.io/SwiftLint/rule-directory.html).

You can also check the
[Source/SwiftLintBuiltInRules/Rules](https://github.com/realm/SwiftLint/tree/main/Source/SwiftLintBuiltInRules/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:

```swift
// 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:

```swift
// 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:

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

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

### Configuration

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

Rule inclusion:

* `disabled_rules`: Disable rules from the default enabled set.
* `opt_in_rules`: Enable rules that are not part of the default set. The
   special `all` identifier will enable all opt in linter rules, except the ones
   listed in `disabled_rules`.
* `only_rules`: Only the rules specified in this list will be enabled.
   Cannot 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 are no equivalents for `disabled_rules`
  and `only_rules`. The special `all` identifier can also be used here to enable
  all analyzer rules, except the ones listed in `disabled_rules`.

```
/* Detailed source-code truncated for AI context efficiency. */
```

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

### Defining Custom Rules

In addition to the rules that the main SwiftLint project ships with, SwiftLint
can also run two types of custom rules that you can define yourself in your own
projects:

#### 1. Swift Custom Rules

These rules are written the same way as the Swift-based rules that ship with
SwiftLint so they're fast, accurate, can leverage SwiftSyntax, can be unit
tested, and more.

Using these requires building SwiftLint with Bazel as described in
[this video](https://vimeo.com/820572803) or its associated code in
[github.com/jpsim/swiftlint-bazel-example](https://github.com/jpsim/swiftlint-bazel-example).

#### 2. Regex Custom Rules

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

```yaml
custom_rules:
  # Rule identifier.
  pirates_beat_ninjas:
    # Optional regex that defines paths to include during linting.
    included:
      - ".*\\.swift"
    # Optional regex that defines paths to exclude during linting.
    excluded:
      - ".*Test\\.swift"
    # Optional rule name.
    name: "Pirates Beat Ninjas"
    # Matching pattern.
    regex: "([nN]inja)"
    # Number of regex capture group to highlight the rule violation at. Optional, defaults to 0 (the whole match).
    capture_group: 0
    # SyntaxKinds to match. optional.
    match_kinds:
      - comment
      - identifier
    # Optional violation message.
    message: "Pirates are better than ninjas."
    # Optional violation severity.
    severity: error
  no_hiding_in_strings:
    regex: "([nN]inja)"
    # Syntax kinds to match. optional.
    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
flags `s` and `m` enabled, that is `.`
[matches newlines](https://developer.apple.com/documentation/foundation/nsregularexpression/options/1412529-dotmatcheslineseparators)
and `^`/`$`
[match the start and end of lines](https://developer.apple.com/documentation/foundation/nsregularexpression/options/1408263-anchorsmatchlines),
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 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`

All syntax kinds used in a snippet of Swift code can be extracted asking
[SourceKitten](https://github.com/jpsim/SourceKitten). For example,
`sourcekitten syntax --text "struct S {}"` delivers

* `source.lang.swift.syntaxtype.keyword` for the `struct` keyword and
* `source.lang.swift.syntaxtype.identifier` for its name `S`

which match to `keyword` and `identifier` in the above list.

If using custom rules in combination with `only_rules`, you must include the
literal string `custom_rules` in the `only_rules` list:

```yaml
only_rules:
  - custom_rules

custom_rules:
  no_hiding_in_strings:
    regex: "([nN]inja)"
    match_kinds: string
```

Unlike Swift custom rules, you can use official SwiftLint builds
(e.g. from Homebrew) to run regex custom rules.

### Auto-correct

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

Please make sure to have backups of these files before running
`swiftlint --fix`, 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

The `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

1. Cleaning DerivedData (incremental builds won't work with analyze)
2. Running `xcodebuild -workspace {WORKSPACE}.xcworkspace -scheme {SCHEME} > xcodebuild.log`
3. Running `swiftlint analyze --compiler-log-path xcodebuild.log`

Analyzer rules tend to be considerably slower than lint rules.

## Using Multiple Configuration Files

SwiftLint offers a variety of ways to include multiple configuration files.
Multiple configuration files get merged into one single configuration that is
then applied just 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 overrides in each project via a child configuration file.

Team-Wide Configuration:

```yaml
disabled_rules:
  - force_cast
```

Project-Specific Configuration:

```yaml
opt_in_rules:
  - force_cast
```

### Child/Parent Configs (Locally)

You can specify a `child_config` and/or a `parent_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 thus 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:

```txt
ProjectRoot
    |_ .swiftlint.yml
    |_ .swiftlint_refinement.yml
    |_ Base
        |_ .swiftlint_base.yml
```

To include both the refinement and the base file, your `.swiftlint.yml` should
look like this:

```yaml
child_config: .swiftlint_refinement.yml
parent_config: Base/.swiftlint_base.yml
```

When merging parent and child configs, `included` and `excluded` configurations
are processed carefully to account for differences in the directory location
of the containing configuration files.

Path merging follows these rules:

1. `included`/`excluded` entries from each config are resolved relative to that
   config file's directory.
2. Child entries override conflicting parent entries.
3. The merged path lists are computed as:

```text
merged.included = (parent.included - child.excluded) + child.included
merged.excluded = (parent.excluded - child.included) + child.excluded
```

This means a child config can re-include a path excluded by its parent and can
exclude a path included by its parent.

### Child/Parent Configs (Remote)

Just as you can provide local `child_config`/`parent_config` references,
instead of referencing local paths, you can just put urls that lead to
configuration files. In order for SwiftLint to detect these remote references,
they must start with `http://` or `https://`.

The referenced remote configuration files may even recursively reference other
remote configuration files, but aren't allowed to include local references.

Using a remote reference, your `.swiftlint.yml` could look like this:

```yaml
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 of every remote configuration that is referenced. If this
request times out, a cached version is used if available. If there is no cached
version available, SwiftLint fails – but no worries, a cached version should be
there once SwiftLint has run successfully at least once.

If needed, the timeouts for the remote configuration fetching can be specified
manually via the configuration file(s) using the
`remote_timeout`/`remote_timeout_if_cached` specifiers. These values default
to 2 seconds or 1 second, respectively.

### Command Line

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`

### Nested Configurations

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 structure. For a given file, SwiftLint walks up from that file's
directory towards the root configuration and uses the first nested
`.swiftlint.yml` it finds as a child config.

That nested config applies only to files in its directory subtree. Files in
other subtrees continue using the main config (or their own nearest nested
config).

Because SwiftLint stops at the first match while walking up the directory tree,
**at most one nested configuration is merged per file** (in addition to the
main configuration).

`.swiftlint.yml` files are only considered as a nested configuration if they
have not been used to build the main configuration already (e. g. by having
been referenced via something like `child_config: Folder/.swiftlint.yml`).
Also, `parent_config`/`child_config` specifications 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 exist other `.swiftlint.yml` files somewhere within the directory.
**So if you want to use nested configurations, you can't use the `--config`
parameter.**

## License

[MIT licensed.](https://github.com/realm/SwiftLint/blob/main/LICENSE)

## About

SwiftLint is utterly maintained by volunteers contributing to its success
entirely in their free time. As such, SwiftLint isn't a commercial product
in any way.

Be kind to the people maintaining SwiftLint as a hobby and accept that their
time is limited. Support them by contributing to the project, reporting issues,
and helping others in the community.

Special thanks go to [MacStadium](https://www.macstadium.com) for providing
physical Mac mini machines to run our performance tests.



We also thank Realm (now MongoDB) for their initial contributions and setup of
the project.

---

## File: README_CN.md

# SwiftLint

SwiftLint 是一个用于强制检查 Swift 代码风格和规定的一个工具，基本上以 [Kodeco's Swift 代码风格指南](https://github.com/kodecocodes/swift-style-guide)为基础。

SwiftLint Hook 了 [Clang](http://clang.llvm.org) 和 [SourceKit](http://www.jpsim.com/uncovering-sourcekit) 从而能够使用 [AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) 来表示源代码文件的更多精确结果。

[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=main)
[](https://codecov.io/github/realm/SwiftLint?branch=main)



该项目遵守 [贡献者契约行为守则](https://realm.io/conduct)。一旦参与，你将被视为支持这一守则。请将
不可接受的行为报告给 [info@realm.io](mailto:info@realm.io)。

## 安装

### 使用[Swift Package Manager](https://github.com/apple/swift-package-manager)

SwiftLint 可以用作[命令插件](#swift-package-command-plugin)或[构建工具插件](#build-tool-plugins)

添加

```swift
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "<version>")
```

到你的 `Package.swift` 文件中，以自动获取 SwiftLint 的最新版本，或者将依赖项固定到特定版本：

```swift
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", exact: "<version>")
```

其中，用所需的最低版本或精确版本替换 `<version>`。

### [Xcode Package Dependency](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app)

使用以下链接将 SwiftLint 作为包依赖添加到 Xcode 项目中：

```bash
https://github.com/SimplyDanny/SwiftLintPlugins
```

### 使用 [Homebrew](http://brew.sh/)

```
brew install swiftlint
```

### 使用 [CocoaPods](https://cocoapods.org)

将如下代码添加到你的 Podfile 即可：

```ruby
pod 'SwiftLint'
```

在下一次执行 `pod install` 时将会把 SwiftLint 的二进制文件和依赖下载到 `Pods/` 目录下并且将允许你通过 `${PODS_ROOT}/SwiftLint/swiftlint` 在 Script Build Phases 中调用 SwiftLint。

自从 SwiftLint 支持安装某个特定版本后，安装一个指定版本的 SwiftLint 是目前推荐的做法相比较于简单地选择最新版本安装的话（比如通过 Homebrew 安装的话）。

请注意这会将 SwiftLint 二进制文件、所依赖的二进制文件和 Swift 二进制库安装到 `Pods/` 目录下，所以不推荐将此目录添加到版本控制系统（如 git）中进行跟踪。

### 使用 [Mint](https://github.com/yonaskolb/mint)

```
mint install realm/SwiftLint
```

### 使用安装包

你也可以通过从[最新的 GitHub 发布地址](https://github.com/realm/SwiftLint/releases/latest)下载 `SwiftLint.pkg` 然后执行的方式安装 SwiftLint。

### 编译源代码

你也可以通过 clone SwiftLint 的 Git 仓库到本地然后执行
`make install` (Xcode 15.0+) 以从源代码构建及安装。

### 使用 Bazel

把这个放到你的 `MODULE.bazel`：

```bzl
bazel_dep(name = "swiftlint", version = "0.50.4", repo_name = "SwiftLint")
```

或把它放到你的 `WORKSPACE`：



WORKSPACE

```bzl
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()
```



然后你就可以在当前目录下使用这个命令运行 SwiftLint：

```console
bazel run -c opt @SwiftLint//:swiftlint
```

## 用法

### 报告

我们鼓励你观看本次报告，来获得将 SwiftLint 整合到你的项目中的推荐方式的一个高层次概括：

[](https://youtu.be/9Z1nTMTejqU)

### Xcode

整合 SwiftLint 到 Xcode 体系中去从而可以使警告和错误显示到 IDE 上，只需要在 Xcode 中添加一个新的“Run Script Phase”并且包含如下代码即可：



Xcode 15 对 Build Settings 进行了重大更改，它将 `ENABLE_USER_SCRIPT_SANDBOXING` 的默认值从 `NO` 更改为 `YES`。
因此，SwiftLint 会遇到与缺少文件权限相关的错误，通常报错信息为：`error: Sandbox: swiftlint(19427) deny(1) file-read-data.`

要解决此问题，需要手动将 `ENABLE_USER_SCRIPT_SANDBOXING` 设置为 `NO`，以针对 SwiftLint 配置的特定目标。

如果你是在搭载 Apple 芯片的 Mac 上通过 Homebrew 安装的 SwiftLint，你可能会遇到这个警告：

> warning: SwiftLint not installed, download from <https://github.com/realm/SwiftLint>

这是因为 Homebrew 在搭载 Apple 芯片的 Mac 上将二进制文件默认安装到了 `/opt/homebrew/bin`
下。如果要让 Xcode 知道 SwiftLint 在哪，你可以在 Build Phase 中将
`/opt/homebrew/bin` 路径添加到 `PATH` 环境变量

```bash
if [[ "$(uname -m)" == arm64 ]]; then
    export PATH="/opt/homebrew/bin:$PATH"
fi

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

或者，你可以创建一个指向在 `/usr/local/bin` 中实际二进制文件的符号链接：

```bash
ln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlint
```

你可能希望将SwiftLint阶段直接移到'Compile Sources'
步骤之前，以便在编译之前快速检测错误。但是，SwiftLint 被设计
为在有效的 Swift 代码上运行，这些代码干净利落地完成了编译器的解析阶段。
因此，在'Compile Sources'之前运行 SwiftLint 可能会产生一些不正确的结果。

如果你也希望修正违规行为，你的脚本可以运行
`swiftlint --fix && swiftlint` 而不是 `swiftlint`。 这将意味着
修复所有可纠正的违规行为，同时确保在你的项目中对剩余的违规行为显示警告。

如果你已经通过 CocoaPods 安装了 SwiftLint，脚本看起来应该像这样：

```bash
"${PODS_ROOT}/SwiftLint/swiftlint"
```

### 插件支持

SwiftLint 既可以作为 Xcode 项目构建工具，也可以作为 Swift package。

> 由于 Swift Package Manager 插件的限制，仅推荐
> 在其根目录中有 SwiftLint 配置的项目使用，因为
目前没有办法将任何附加选项传递给 SwiftLint 可执行文件。

#### Xcode

如果你正在使用 Xcode 中的项目，你可以将 SwiftLint 集成为
Xcode 构建工具插件。

将 SwiftLint 作为依赖包添加到你的项目中，无需链接任何其他服务。

选择要添加修正的目标，打开 `Build Phases` 检查器。
打开 `Run Build Tool Plug-ins` 并选择 `+` 按钮。
从列表中选择 `SwiftLintBuildToolPlugin` 并将其添加到项目中。



对于无人值守的使用场景（例如在 CI 上），可以通过以下方式禁用软件包和宏的验证对话框

* 单独将 `-skipPackagePluginValidation` 和 `-skipMacroValidation` 传递到 `xcodebuild` 或者
* 为那个用户使用 `defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES` 进行全局设置，然后写入 `defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES`

_注意：这将隐含地信任所有的Xcode软件包插件，并绕过Xcode的软件包验证对话框。
       这对安全有影响。_

#### Swift Package

你可以将 SwiftLint 集成为 Swift Package Manager 插件，如果你正在使用
具有 `Package.swift` 清单的 Swift 包。

将 SwiftLint 作为包依赖添加到你的 `Package.swift` 文件中。  
使用`plugins`参数将SwiftLint添加到目标。

```swift
.target(
    ...
    plugins: [.plugin(name: "SwiftLintPlugin", package: "SwiftLint")]
),
```

### Visual Studio Code

如果要在[vscode](https://code.visualstudio.com)上使用 SwiftLint，在应用市场上安装
[`vscode-swiftlint`](https://marketplace.visualstudio.com/items?itemName=vknabel.vscode-swiftlint)扩展。

### fastlane

你可以用[fastlane官方的SwiftLint功能](https://docs.fastlane.tools/actions/swiftlint)来运行 SwiftLint 作为你的 Fastlane 程序的一部分。

```ruby
swiftlint(
    mode: :lint,                            # SwiftLint模式: :lint (默认) 或者 :autocorrect
    executable: "Pods/SwiftLint/swiftlint", # SwiftLint的程序路径 (可选的). 对于用CocoaPods集成SwiftLint时很重要
    path: "/path/to/lint",                  # 特殊的检查路径 (可选的)
    output_file: "swiftlint.result.json",   # 检查结果输出路径 (可选的)
    reporter: "json",                       # 输出格式 (可选的)
    config_file: ".swiftlint-ci.yml",       # 配置文件的路径 (可选的)
    files: [                                # 指定检查文件列表 (可选的)
        "AppDelegate.swift",
        "path/to/project/Model.swift"
    ],
    ignore_exit_status: true,               # 允许fastlane可以继续执行甚至是Swiftlint返回一个非0的退出状态(默认值: false)
    quiet: true,                            # 不输出像‘Linting’和‘Done Linting’的状态日志 (默认值: false)
    strict: true                            # 发现警告时报错? (默认值: false)
)
```

### Docker

`swiftlint` 也可以在 [Docker](https://www.docker.com/) 上使用 `Ubuntu` 作为一个镜像使用。
因此，第一次你需要使用下面的命令调用 docker 镜像：

```bash
docker pull ghcr.io/realm/swiftlint:latest
```

接下来，你只需在 docker 中运行`swiftlint`：

```bash
docker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latest
```

这将在你现在所在的文件夹（`pwd`）中执行`swiftlint`，显示类似的输出：

```bash
$ docker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latest
Linting Swift files in current working directory
Linting 'RuleDocumentation.swift' (1/490)
...
Linting 'YamlSwiftLintTests.swift' (490/490)
Done linting! Found 0 violations, 0 serious in 490 files.
```

这里有更多关于使用[Docker 镜像](https://docs.docker.com/)的文档。

### 命令行

```
$ swiftlint help
Available commands:

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

在包含有需要执行代码分析的 Swift 源码文件的目录下执行 `swiftlint` 命令，会对目录进行递归查找。

当使用 `lint` 或者 `autocorrect` 命令时，你可以通过添加 `--use-script-input-files` 选项并且设置以下实例变量：`SCRIPT_INPUT_FILE_COUNT` 和
`SCRIPT_INPUT_FILE_0`, `SCRIPT_INPUT_FILE_1`... `SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT - 1}` 的方式来指定一个文件列表（就像被 Xcode 特别是 [`ExtraBuildPhase`](https://github.com/norio-nomura/ExtraBuildPhase) Xcode 插件修改的文件组成的列表，或者类似 Git 工作树中 `git ls-files -m` 命令显示的被修改的文件列表）。

也有类似的用来设置输入文件的环境变量以 [自定义 Xcode script phases](http://indiestack.com/2014/12/speeding-up-custom-script-phases/) 。

### 使用多个 Swift 版本

SwiftLint 工作于 SourceKit 这一层，所以 Swift 版本发生变化时它也能继续工作！

这也是 SwiftLint 轻量化的原因，因为它不需要一个完整的 Swift 编译器，它只是与已经安装在你的电脑上的官方编译器进行通信。

你应该总是使用和你编译代码同样的工具集来执行 SwiftLint。

如果你有多套工具集或者安装了多个不同版本的 Xcode，你可能会需要覆盖 SwiftLint 默认的工具集。

下面这些命令可以控制 SwiftLint 使用哪一个 Swift 工具集来进行工作：

* `$XCODE_DEFAULT_TOOLCHAIN_OVERRIDE`
* `$TOOLCHAIN_DIR` 或者 `$TOOLCHAINS`
* `xcrun -find swift`
* `/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`
* `/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`
* `~/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`
* `~/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`

`sourcekitd.framework` 默认需要位于 `usr/lib/` 中，上面传入的路径的子目录中。

你可能也给反向 DNS 符号设置了 `TOOLCHAINS` 环境变量来标记一个特定的 Swift 工具集版本：

```shell
TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint autocorrect
```

在 Linux 上，SourceKit 默认需要位于 `/usr/lib/libsourcekitdInProc.so` 或者通过 `LINUX_SOURCEKIT_LIB_PATH` 环境变量进行指定。

### 预提交

SwiftLint 可以作为一个 [预提交](https://pre-commit.com/) 钩子运行。
一当 [安装](https://pre-commit.com/#install)，把这个添加到在 root 路径中的
`.pre-commit-config.yaml` 里：

```yaml
repos:
  - repo: https://github.com/realm/SwiftLint
    rev: 0.50.3
    hooks:
      - id: swiftlint
```

将 `rev` 调整为您选择的 SwiftLint 版本。可以使用 `pre-commit autoupdate` 来更新到当前版本。

SwiftLint 可以使用 `entry` 进行配置以应用修复和报错：

```yaml
-   repo: https://github.com/realm/SwiftLint
    rev: 0.50.3
    hooks:
    -   id: swiftlint
        entry: swiftlint --fix --strict
```

## 规则

SwiftLint 已经包含了超过 200 条规则，并且我们希望 Swift 社区（就是你！）会在以后有更多的贡献，我们鼓励提交 [Pull Requests](CONTRIBUTING.md)。

你可以在 [这里](https://realm.github.io/SwiftLint/rule-directory.html) 找到规则的更新列表和更多信息。

你也可以查看 [Source/SwiftLintBuiltInRules/Rules](Source/SwiftLintBuiltInRules/Rules) 目录来查看它们的实现。

### Opt-In 规则

`opt_in_rules` 默认是关闭的（即，你需要在你的配置文件中明确地打开它们）。

什么时候需要将一个规则设为 opt-in 的指南：

* 一个可能会有许多负面作用的规则（例如 `empty_count`）
* 一个过慢的规则
* 一个不通用或者仅在某些特定场景下可用的规则（例如 `force_unwrapping`）

### 在代码中关闭某个规则

可以通过在一个源文件中定义一个如下格式的注释来关闭某个规则：

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

在该文件结束之前或者在定义如下格式的匹配注释之前，这条规则都会被禁用：

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

例如：

```swift
// 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
```

包含 "all "关键字将禁用所有的规则，直到 linter 看到匹配的启用注释：

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

例如：

```swift
// 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
```

也可以通过添加`:previous`、`:this`或`:next`来修改`disable`或`enable`命令，
使它们只对前一行，当前或者后一行代码有效。

例如：

```swift
// 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
```

执行 `swiftlint rules` 命令可以输出所有可用的规则和他们的标识符组成的列表。

### 配置

可以通过在你需要执行 SwiftLint 的目录下添加一个 `.swiftlint.yml` 文件的方式来配置 SwiftLint。可以被配置的参数有：

包含的规则：

* `disabled_rules`: 关闭某些默认开启的规则。
* `opt_in_rules`: 一些规则是可选的。
* `only_rules`: 不可以和 `disabled_rules` 或者 `opt_in_rules` 并列。类似一个白名单，只有在这个列表中的规则才是开启的。

```yaml
disabled_rules: # 执行时排除掉的规则
  - colon
  - comma
  - control_statement
opt_in_rules: # 一些规则是默认关闭的，所以你需要手动启用
  - empty_count # 你可以通过执行如下指令来查找所有可用的规则：`swiftlint rules`
# 或者，通过取消对该选项的注释来明确指定所有规则：
# only_rules：# 如果使用，请删除 `disabled_rules` 或 `opt_in_rules`
#   - empty_parameters
#   - vertical_whitespace

analyzer_rules: # `swiftlint analyze` 运行的规则
  - explicit_self

included: # 执行 linting 时包含的路径。如果出现这个 `--path` 会被忽略。
  - Sources
excluded: # 执行 linting 时忽略的路径。 优先级比 `included` 更高。
  - Carthage
  - Pods
  - Sources/ExcludedFolder
  - Sources/ExcludedFile.swift

# 如果值为 true，SwiftLint 将把所有警告都视为错误
strict: false

# 可配置的规则可以通过这个配置文件来自定义
# 二进制规则可以设置他们的严格程度
force_cast: warning # 隐式
force_try:
  severity: warning # 显式
# 同时有警告和错误等级的规则，可以只设置它的警告等级
# 隐式
line_length: 110
# 可以通过一个数组同时进行隐式设置
type_body_length:
  - 300 # warning
  - 400 # error
# 或者也可以同时进行显式设置
file_length:
  warning: 500
  error: 1200
# 命名规则可以设置最小长度和最大程度的警告/错误
# 此外它们也可以设置排除在外的名字
type_name:
  min_length: 4 # 只是警告
  max_length: # 警告和错误
    warning: 40
    error: 50
  excluded: iPhone # 排除某个名字
identifier_name:
  min_length: # 只有最小长度
    error: 4 # 只有错误
  excluded: # 排除某些名字
    - id
    - URL
    - GlobalAPIKey
reporter: "xcode" # 报告类型 (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging)
```

#### 定义自定义规则

你可以用如下语法在你的配置文件里定义基于正则表达式的自定义规则：

```yaml
custom_rules:
  pirates_beat_ninjas: # 规则标识符
    name: "Pirates Beat Ninjas" # 规则名称，可选
    regex: "([nN]inja)" # 匹配的模式
    match_kinds: # 需要匹配的语法类型，可选
      - comment
      - identifier
    message: "Pirates are better than ninjas." # 提示信息，可选
    severity: error # 提示的级别，可选
  no_hiding_in_strings:
    regex: "([nN]inja)"
    match_kinds: string
```

输出大概可能是这个样子的：



你可以通过提供一个或者多个 `match_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

#### 嵌套配置

SwiftLint 支持通过嵌套配置文件的方式来对代码分析过程进行更加细致的控制。

* 在你需要的目录引入 `.swiftlint.yml`。
* 在目录结构必要的地方引入额外的 `.swiftlint.yml` 文件。
* 每个文件被检查时会使用在文件所在目录下的或者父目录的更深层目录下的配置文件。否则根配置文件将会生效。
* `excluded` 和 `included` 在嵌套结构中会被忽略。

### 自动更正

SwiftLint 可以自动修正某些错误，磁盘上的文件会被一个修正后的版本覆盖。

请确保在对文件执行 `swiftlint autocorrect` 之前有对它们做过备份，否则的话有可能导致重要数据的丢失。

因为在执行自动更正修改某个文件后很有可能导致之前生成的代码检查信息无效或者不正确，所以当在执行代码更正时标准的检查是无法使用的。

## 协议

[MIT 许可。](LICENSE)

## 关于



SwiftLint 是由 Realm Inc 建立和维护的。Realm 的名字和标志是属于 Realm Inc 的注册商标。

我们 :heart: 开源软件！看一下[我们的其他开源项目](https://github.com/realm)，瞅一眼[我们的博客](https://realm.io/news)，或者在推特上跟我们唠唠嗑([@realm](https://twitter.com/realm))。



感谢 MacStadium 为我们的性能测试提供了一台 Mac Mini。

---

## File: README_KR.md

# SwiftLint

SwiftLint는 스위프트 스타일 및 컨벤션을 강제하기 위한 도구로, [Kodeco 스위프트 스타일 가이드](https://github.com/kodecocodes/swift-style-guide)에 대략적인 기반을 두고 있습니다.

SwiftLint는 좀 더 정확한 결과를 위해 [Clang](http://clang.llvm.org)과 [SourceKit](http://www.jpsim.com/uncovering-sourcekit)에 연결하여 소스 파일의 [AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) 표현을 사용합니다.

[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=main)
[](https://codecov.io/github/realm/SwiftLint?branch=main)



본 프로젝트는 [Contributor Covenant Code of Conduct](https://realm.io/conduct)를 충실히 따릅니다. 본 프로젝트에 참여함으로써 이러한 수칙을 준수해야 합니다. 받아들일 수 없는 항목이 있다면 [info@realm.io](mailto:info@realm.io)로 알려주세요.

## 설치 방법

### [Homebrew](http://brew.sh/)를 사용하는 경우

```
brew install swiftlint
```

### [CocoaPods](https://cocoapods.org)을 사용하는 경우

Podfile에 아래 라인을 추가하기만 하면 됩니다.

```ruby
pod 'SwiftLint'
```

이를 실행하면 다음 번 `pod install` 실행 시 SwiftLint 바이너리 및 `Pods/`에 있는 의존성들을 다운로드하고, Script Build Phases에서 `${PODS_ROOT}/SwiftLint/swiftlint` 명령을 사용할 수 있게 됩니다.

CocoaPods을 사용하면 최신 버전 외에도 SwiftLint의 특정 버전을 설치할 수 있기 때문에 이 방법을 권장합니다. (Homebrew는 최신 버전만 설치 가능)

이렇게 했을 때 SwiftLint 바이너리 및 그에 종속된 바이너리들과 스위프트 바이너리까지 `Pods/` 디렉터리에 추가되기 때문에, git 등의 SCM에 이런 디렉터리들을 체크인하는 것은 권장하지 않습니다.

### [Mint](https://github.com/yonaskolb/mint)를 사용하는 경우

```
mint install realm/SwiftLint
```

### 빌드된 패키지를 사용하는 경우

[최신 깃허브 릴리즈](https://github.com/realm/SwiftLint/releases/latest)에서 `SwiftLint.pkg`를 다운로드해서 설치하고 실행할 수 있습니다.

### 소스를 직접 컴파일하는 경우

본 프로젝트를 클론해서 빌드할 수도 있습니다. `make install` 명령을 사용합니다. (Xcode 12.5 이후 버전)

## 사용 방법

### 프레젠테이션

프로젝트에 SwiftLint를 통합하기 위한 권장 사용 방식의 전반적인 개요를 알고 싶다면, 아래 프레젠테이션 영상을 보거나 스크립트를 읽어보면 좋습니다.

[](https://youtu.be/9Z1nTMTejqU)

### Xcode

SwiftLint를 Xcode 프로젝트에 통합하여 IDE 상에 경고나 에러를 표시할 수 있습니다. 프로젝트의 파일 내비게이터에서 타겟 앱을 선택 후 "Build Phases" 탭으로 이동합니다. + 버튼을 클릭한 후 "Run Script Phase"를 선택합니다. 그 후 아래 스크립트를 추가하기만 하면 됩니다.

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



만약, 애플 실리콘 환경에서 Homebrew를 통해 SwiftLint를 설치했다면, 아마도 다음과 같은 경고를 겪었을 것입니다.

> warning: SwiftLint not installed, download from <https://github.com/realm/SwiftLint>

그 이유는, 애플 실리콘 기반 맥에서 Homebrew는 기본적으로 바이너리들을 `/opt/homebrew/bin`에 저장하기 때문입니다. SwiftLint가 어디 있는지 찾는 것을 Xcode에 알려주기 위해, build phase에서 `/opt/homebrew/bin`를 `PATH` 환경 변수에 동시에 추가하여야 합니다.

```bash
if [[ "$(uname -m)" == arm64 ]]; then
    export PATH="/opt/homebrew/bin:$PATH"
fi

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

혹은 아래와 같이 `/usr/local/bin`에 심볼릭 링크를 생성하여 실제 바이너리가 있는 곳으로 포인팅할 수 있습니다. :

```bash
ln -s /opt/homebrew/bin/swiftlint /usr/local/bin/swiftlint
```

당신은 SwiftLint phase를 'Compile Sources' 단계 직전으로 옮겨 컴파일 전에 에러를 빠르게 찾고 싶어 할 것입니다. 하지만, SwiftLint는 컴파일러의 구문 분석 단계를 완벽히 수행하는 유효한 Swift 코드를 실행하기 위해 설계되었습니다. 따라서, 'Compile Sources' 전에 SwiftLint를 실행하면 일부 부정확한 오류가 발생할 수도 있습니다.

만약 당신이 위반 사항(violations)을 동시에 수정하는 것을 원한다면, 스크립트에 `swiftlint` 대신 `swiftlint --fix && swiftlint`을 적어야 합니다. 이는 프로젝트의 수정 가능한 모든 위반 사항들이 수정되고 나머지 위반 사항에 대한 경고가 표시된다는 것을 의미합니다.

CocoaPods을 사용해서 설치한 경우는 아래 스크립트를 대신 사용합니다.

```bash
"${PODS_ROOT}/SwiftLint/swiftlint"
```

#### Xcode 저장시 실행되는 플러그인

Xcode에서 저장시 `swiftlint autocorrect`를 실행하려면 Alcatraz에서 [SwiftLintXcode](https://github.com/ypresto/SwiftLintXcode) 플러그인을 설치합니다.

⚠ ️이 플러그인은 Xcode 8에서 SIP를 비활성화하지 않으면 동작하지 않으며, 이는 권장하지 않습니다.

### AppCode

AppCode에서 SwiftLint를 사용하려면 [이 플러그인](https://plugins.jetbrains.com/plugin/9175)을 설치하고 플러그인 환경설정에서 SwiftLint가 설치된 경로를 지정해줍니다. `autocorrect` 액션은 `⌥⏎` 단축키로 사용할 수 있습니다.

### Atom

[Atom](https://atom.io/)에서 SwiftLint를 사용하려면 APM에서 [`linter-swiftlint`](https://atom.io/packages/linter-swiftlint) 패키지를 설치합니다.

### fastlane

fastlane 과정에서 SwiftLint를 사용하려면 [공식적인 fastlane 액션](https://docs.fastlane.tools/actions/swiftlint)를 사용할 수 있습니다.

```ruby
swiftlint(
  mode: :lint,                            # SwiftLint 모드: :lint (디폴트) 아니면 :autocorrect
  executable: "Pods/SwiftLint/swiftlint", # SwiftLint 바이너리 경로 (선택 가능). CocoaPods을 사용해서 설치한 경우는 이 옵션이 중요합니다
  output_file: "swiftlint.result.json",   # 결과 파일의 경로 (선택 가능)
  reporter: "json",                       # 보고 유형 (선택 가능)
  config_file: ".swiftlint-ci.yml",       # 설정 파일의 경로 (선택 가능)
  ignore_exit_status: true                # SwiftLint 종료할 때 0이 아닌 반환한 종료 코드를 무시해서 fastlane 계속 실행합니다
)
```

### 커맨드 라인

```
$ swiftlint help
Available commands:

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

스위프트 파일이 있는 디렉터리에서 `swiftlint`를 실행합니다. 디렉터리는 재귀적으로 탐색됩니다.

`lint`나 `autocorrect`를 사용할 때 여러 파일(예를 들면, [`ExtraBuildPhase`](https://github.com/norio-nomura/ExtraBuildPhase) 플러그인에 의해 Xcode가 변경한 파일들 혹은 `git ls-files -m` 명령으로 인해 작업 트리에서 변경된 파일들)을 지정하려면 `--use-script-input-files` 옵션을 넘기고 다음 인스턴스 변수들을 설정하면 됩니다. `SCRIPT_INPUT_FILE_COUNT` and
`SCRIPT_INPUT_FILE_0`, `SCRIPT_INPUT_FILE_1`...`SCRIPT_INPUT_FILE_{SCRIPT_INPUT_FILE_COUNT - 1}`

이는 [Xcode의 커스텀 스크립트 단계](http://indiestack.com/2014/12/speeding-up-custom-script-phases/)에 입력 파일로 환경 변수를 지정하는 것과 동일합니다.

### 스위프트 여러 버전에 대한 대응

SwiftLint는 SourceKit에 연결되어 있으므로 스위프트 언어가 변화하더라도 이상 없이 동작할 수 있습니다.

이는 전체 스위프트 컴파일러가 포함되지 않아도 되므로 SwiftLint가 간결하게 유지될 수 있습니다. SwiftLint는 데스크탑에 이미 설치되어 있는 공식 스위프트 컴파일러와 통신하기만 하면 됩니다.

SwiftLint를 실행할 때는 항상 스위프트 파일을 컴파일하는 동일한 툴체인을 사용해야 합니다.

설치된 툴체인이나 Xcode가 여러 개인 경우 혹은 스위프트 구 버전을 사용해야 하는 경우(Xcode 8에서 스위프트 2.3 버전을 사용하는 경우)에는 SwiftLint의 기본 스위프트 툴체인을 변경해야 할 수도 있습니다.

SwiftLint가 어느 스위프트 툴체인을 사용할지 결정하는 순서는 다음과 같습니다.

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

`sourcekitd.framework`은 위에서 선택된 경로의 `usr/lib/` 하위 디렉터리에 존재해야 합니다.

`TOOLCHAINS` 환경 변수에 스위프트 툴체인 버전을 식별할 수 있는 값을 리버스 DNS 형식으로 지정할 수도 있습니다.

```shell
TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint autocorrect
```

리눅스에서는 SourceKit이 `/usr/lib/libsourcekitdInProc.so` 혹은 `LINUX_SOURCEKIT_LIB_PATH` 환경변수로 지정된 경로에 존재해야 합니다.

## 룰

SwiftLint에는 200개가 넘는 룰들이 있고, 스위프트 커뮤니티(바로 여러분들!)는 이를 지속적으로 발전시켜 가고 있습니다. [풀 리퀘스트](CONTRIBUTING.md)는 언제나 환영입니다.

현재 구현된 룰 전체를 확인하려면 [Source/SwiftLintBuiltInRules/Rules](Source/SwiftLintBuiltInRules/Rules)를 살펴보세요.

`opt_in_rules`는 기본적으로 비활성화되어 있습니다. (즉, 설정 파일에서 명시적으로 해당 룰을 활성화해야 합니다.)

다음은 룰을 옵트 인으로 구현하는 경우에 대한 기준입니다.

- 잘못 판단될 가능성이 많은 룰 (예: `empty_count`)
- 속도가 매우 느린 룰
- 일반적으로 모든 사람이 합의하지 않거나 특정한 상황에만 유용한 룰 (예: `force_unwrapping`, `missing_docs`)

### 코드에서 룰 비활성화하기

소스 파일에서 아래 형식의 주석을 사용하면 룰을 비활성화할 수 있습니다.

`// swiftlint:disable <룰1> [<룰2> <룰3>...]`

비활성화된 룰은 해당 파일의 마지막까지 적용되거나, 활성화 주석이 나타날 때까지 적용됩니다.

`// swiftlint:enable <룰1> [<룰2> <룰3>...]`

예를 들면 다음과 같습니다.

```swift
// swiftlint:disable colon
let noWarning :String = "" // 변수명 바로 뒤에 콜론이 위치하지 않는다고 경고가 뜨지 않습니다!
// swiftlint:enable colon
let hasWarning :String = "" // 변수명 바로 뒤에 콜론이 위치해야 한다는 경고가 표시됩니다.
```

`disable`과 `enable` 명령 뒤에 `:previous`, `:this`, `:next`를 붙이면 각각 명령이 위치한 이전 라인, 현재 라인, 다음 라인만 룰이 적용되게 할 수 있습니다.

예를 들면 다음과 같습니다.

```swift
// 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
```

`swiftlint rules`를 실행하면 모든 룰 목록과 룰별 식별자가 표시됩니다.

### 설정

SwiftLint가 실행될 디렉터리에 `.swiftlint.yml` 파일을 추가해서 SwiftLint를 설정할 수 있습니다. 아래 파라미터들을 설정 가능합니다.

룰 적용 여부 설정:

- `disabled_rules`: 기본 활성화된 룰 중에 비활성화할 룰들을 지정합니다.
- `opt_in_rules`: 기본 룰이 아닌 룰들을 활성화합니다.
- `only_rules`: 지정한 룰들만 활성화되도록 화이트리스트로 지정합니다. `disabled_rules` 또는 `opt_in_rules`와 함께 사용할 수 없습니다.

```yaml
disabled_rules: # 실행에서 제외할 룰 식별자들
  - colon
  - comma
  - control_statement
opt_in_rules: # 일부 룰은 옵트 인 형태로 제공
  - empty_count
  - missing_docs
  # 사용 가능한 모든 룰은 swiftlint rules 명령으로 확인 가능
included: # 린트 과정에 포함할 파일 경로. 이 항목이 존재하면 `--path`는 무시됨
  - Sources
excluded: # 린트 과정에서 무시할 파일 경로. `included`보다 우선순위 높음
  - Carthage
  - Pods
  - Sources/ExcludedFolder
  - Sources/ExcludedFile.swift

# 설정 가능한 룰은 이 설정 파일에서 커스터마이징 가능
# 경고나 에러 중 하나를 발생시키는 룰은 위반 수준을 설정 가능
force_cast: warning # 암시적으로 지정
force_try:
  severity: warning # 명시적으로 지정
# 경고 및 에러 둘 다 존재하는 룰의 경우 값을 하나만 지정하면 암시적으로 경고 수준에 설정됨
line_length: 110
# 값을 나열해서 암시적으로 양쪽 다 지정할 수 있음
type_body_length:
  - 300 # 경고
  - 400 # 에러
# 둘 다 명시적으로 지정할 수도 있음
file_length:
  warning: 500
  error: 1200
# 네이밍 룰은 경고/에러에 min_length와 max_length를 각각 설정 가능
# 제외할 이름을 설정할 수 있음
type_name:
  min_length: 4 # 경고에만 적용됨
  max_length: # 경고와 에러 둘 다 적용
    warning: 40
    error: 50
  excluded: iPhone # 제외할 문자열 값 사용
identifier_name:
  min_length: # min_length에서
    error: 4 # 에러만 적용
  excluded: # 제외할 문자열 목록 사용
    - id
    - URL
    - GlobalAPIKey
reporter: "xcode" # 보고 유형 (xcode, json, csv, codeclimate, checkstyle, junit, html, emoji, sonarqube, markdown, github-actions-logging)
```

#### 커스텀 룰 정의

아래 문법을 사용하여 설정 파일에 새로운 정규 표현식 기반의 룰을 정의할 수 있습니다.

```yaml
custom_rules:
  pirates_beat_ninjas: # 룰 식별자
    included: ".*.swift" # 린트 실행 시 포함할 경로를 정의하는 정규표현식. 선택 가능.
    name: "Pirates Beat Ninjas" # 룰 이름. 선택 가능.
    regex: "([nN]inja)" # 패턴 매칭
    match_kinds: # 매칭할 SyntaxKinds. 선택 가능.
      - comment
      - identifier
    message: "Pirates are better than ninjas." # 위반 메시지. 선택 가능.
    severity: error # 위반 수준. 선택 가능.
  no_hiding_in_strings:
    regex: "([nN]inja)"
    match_kinds: string
```

결과는 다음과 같습니다.



하나 이상의 `match_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

#### 중첩 구성

SwiftLint는 설정 파일을 중첩되게 구성해서 린트 과정을 더욱 세밀하게 제어할 수 있습니다.

- 디렉터리 구조에서 필요한 곳이면 어디든지 `.swiftlint.yml` 파일을 추가할 수 있습니다.
- 각 파일은 자신의 디렉터리 내에 있는 설정 파일을 사용하거나, 계층구조 상 가장 가까운 부모 디렉터리에 있는 설정 파일을 사용해서 린트됩니다. 별도로 설정 파일이 존재하지 않으면 루트에 있는 설정 파일이 사용됩니다.
- 중첩 구성에서 `excluded` 및 `included`는 무시됩니다.

### 자동 수정

SwiftLint는 일부 위반 사항들을 자동으로 수정할 수 있습니다. 디스크 상의 파일들은 수정된 버전으로 덮어 쓰여지게 됩니다.

`swiftlint autocorrect`를 실행하기 전에 파일들을 백업해주세요. 그렇지 않으면 중요한 데이터가 유실될 수도 있습니다.

표준 린트 검사는 자동 수정 중에는 비활성화됩니다. 위반 사항들은 파일이 자동 수정된 후에 더이상 유효하지 않을 가능성이 크기 때문입니다.

## 라이선스

[MIT 라이선스.](LICENSE)

## About



SwiftLint는 Realm Inc.에 의해 만들어져서 관리되고 있습니다. Realm의 이름과 로고는 Realm Inc.의 트레이드 마크입니다.

우리는 오픈 소스 소프트웨어를 사랑합니다:heart:! Realm의 [다른 오픈소스 프로젝트](https://github.com/realm)와 [블로그](https://realm.io/news)들도 들러주시고, 트위터([@realm](https://twitter.com/realm))로도 반갑게 인사 주세요.

## 2. Official Technical Reference & Guides (realm/realm.github.io)

Realm Open Source
=========================

A simple, static portal which outlines our open source offerings. Intentionally
themed to look like a merchant page on the directory.



Development
-----------

In an attempt to prevent unnessicary file duplication, the easiest way to develop is by build the static site and replace the index page for the site with the one from `open-source`. By default on realm.io repo the `open-source` page is ignored. Update this page on that repo to keep the footer, header, and site styles consolidated. 

## how to update

    1) make updates to the page running the realm.io repo locally
    2) build the site locally by running `bundle exec middleman build --verbose`
    3) copy the contents of the `/open-source` folder into the root of this repo as well as any page specific style changes
    4) replace the index in `/open-source` with the index of the repo
    5) rename asset paths and URLs to reflect the new page location at the root. 
    6) Push to master