모바일 프로그래밍/IOS참고자료

[Swift] SwiftLint 적용(이미지 수정중)

Dannian 2021. 4. 5. 11:18
반응형
 

realm/SwiftLint

A tool to enforce Swift style and conventions. Contribute to realm/SwiftLint development by creating an account on GitHub.

github.com

이번에는 SwiftLint를 프로젝트에 적용해보려 합니다.

이전부터 계속 적용하고싶었는데, 기존 프로젝트에 적용하려 하니 파일에 영향이 너무 커서 내부 토의를 통해서 차후 적용하는 방향으로 결론이 난 덕분에 지금까지 못 쓰고 있었습니다.

그러다가 이번에 새로운 프로젝트를 하면서 SwiftLint를 처음부터 적용하기로 했습니다.

 

1. SwiftLint란?

SwiftLint란 'Linter'입니다.

Linter란 커뮤니티 또는 팀에서 정한 규칙(변수명, 파일명, 코드 스타일 등)을 따르지 않는 코드를 식별하고 수정하기 용이하도록 표시하는 것을 돕는 것입니다.

아무래도 개발자마다 코딩 스타일이 다르기 때문에 협업을 하다보면 다른사람이 작성한 코드를 보는것이 불편한 부분이 있습니다.

이런것을 방지하기 위해서 코딩표준(코딩 컨벤션)이 있는데, 코드를 작성할 때 추천하는 코딩스타일 등을 모아둔 가이드라인입니다.

이런 코딩 컨벤션을 Rule로 정하여 Swift 코드가 일관성있도록 해주어 새로운 개발자나 기존 개발자들간의 협업이 용이하도록 하는 것입니다.

 

Rule Directory Reference

 

realm.github.io

위의 링크는 SwiftLint의 전체 Rule들을 볼 수 있는 링크입니다.

 

realm/SwiftLint

A tool to enforce Swift style and conventions. Contribute to realm/SwiftLint development by creating an account on GitHub.

github.com

위 링크는 한글로 정리되어있는 SwiftLint 문서입니다.

 

2. SwiftLint 적용하기

저는 CocoaPod기준으로 작성하도록 하겠습니다.

2-1. pod Install

(기존에 pod init이 되어있다는 가정하에) Podfile에 SwiftLint를 추가합니다.

pod 'SwiftLint'

그 후 pod install을 합니다.

2-2. Script 작성

pod install후 projectName.xcworkspace를 열어서 Target -> build phase -> + -> New Run Script Phase를 누릅니다.

//이미지 추가 예정(New Run Script Phase 이미지)

새로 추가된 Run Script에 다음 코드를 추가합니다

"${PODS_ROOT}/SwiftLint/swiftlint" --path "${PROJECT_DIR}/.swiftlint.yml" #autocorrect

(--path 이후 부분에 대해서는 3번 항목에서 이유를 설명하겠습니다.)

autocorrect의 경우에는 일일히 수정하기 귀찮은 경우 적용하면 되는데, 저는 새 프로젝트이기도 하고 굳이 필요가 없어서 주석처리했습니다.

일부 내용을 보니 autocorrect를 적용하면 원치 않는 경우에도 수정이 될 수 있기 때문에 주의하셔야 할 것 같습니다.

 

2-3. .swiftlint.yml 파일 추가

lint의 설정 파일입니다. 이 파일에서 rule들을 enable또는 disable하면서 입맛대로 적용할 수 있습니다.

//Empty file 추가 및 디렉터리 위치 이미지 추가

이 파일을 추가하실 때는 최상위 경로에 추가하셔야합니다.

 

아래는 SwiftLint 공식 문서의 기본 .swiftlint.yml 내용입니다

# By default, SwiftLint uses a set of sensible default rules you can adjust:
disabled_rules: # rule identifiers turned on by default to exclude from running
  - colon
  - comma
  - control_statement
opt_in_rules: # some rules are turned off by default, so you need to opt-in
  - empty_count # Find all the available rules by running: `swiftlint rules`

# Alternatively, specify all rules explicitly by uncommenting this option:
# only_rules: # delete `disabled_rules` & `opt_in_rules` if using this
#   - empty_parameters
#   - vertical_whitespace

included: # paths to include during linting. `--path` is ignored if present.
  - Source
excluded: # paths to ignore during linting. Takes precedence over `included`.
  - Carthage
  - Pods
  - Source/ExcludedFolder
  - Source/ExcludedFile.swift
  - Source/*/ExcludedFile.swift # Exclude files with a wildcard
analyzer_rules: # Rules run by `swiftlint analyze` (experimental)
  - explicit_self

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

 

 

3. 처음 작성시 문제 발생 해결법

저는 이번에 처음 SwiftLint를 적용하는 것이었습니다.

다른 블로그에 소개되어있는대로 설치와 설정을 진행했는데, Run Script에 아래 방식으로 추가를 하면 이미지와 같은 에러가 계속 발생했습니다.

#in Run Script
"${PODS_ROOT}/SwiftLint/swiftlint"

미쳐버리겠네..

여러 해결방법을 찾아봤는데, 이런 문제가 발생하는 경우가 몇가지 있는 듯 했습니다.

  • 경로상 공백이 포함된 경우
  • 키체인 문제

저는 모두 포함되지 않았기 때문에 단순히 해당 디렉토리에서 파일을 못 찾는 문제로 판단을 해서 다음 줄 처럼 수정을 했습니다.

#in Run Script
"${PODS_ROOT}/SwiftLint/swiftlint" --path "${PROJECT_DIR}/.swiftlint.yml"

.swiftlint.yml파일을 분명 프로젝트 디렉터리에 생성했지만, 경로를 잡지 못하는 문제였습니다.

(문제해결 위한 참고 링크)

 

"${PODS_ROOT}/SwiftLint/swiftlint" causes "Command PhaseScriptExecution failed with a nonzero exit code" with Xcode 10

Updating from Xcode 10.0 beta 2 to Xcode 10.0 beta 3 I now get this error at build time for an iOS project: sourcekit: [1:connection-event-handler:10499: 0.0000] Connection interruptsourcekit: [1:

stackoverflow.com

 

No lintable files found at paths SwiftLint

I tried to install SwiftLint using CocoaPods and I add in Build phases the following script : "${PODS_ROOT}/SwiftLint/swiftlint" SwiftLint is installed correctly and I get many errors and warni...

stackoverflow.com

(이것 때문에 한 30분 날렸네요...)

 

.swiftlint.yml에서 included: 부분에 App의 name을 넣어주면 해당 문제가 해결되는 것 확인했습니다. 저는 이 부분을 생략했더라구요.

반응형