[SwiftLint] Xcode에서 프로젝트에 lint 적용하기.
2025. 2. 4. 15:19ㆍ🍏/Xcode
Swift Lint
렘에서 제공하는 Swift Lint를 적용해 보려합니다.
GitHub - realm/SwiftLint: A tool to enforce Swift style and conventions.
A tool to enforce Swift style and conventions. Contribute to realm/SwiftLint development by creating an account on GitHub.
github.com
brew에서 swiftlint 설치
brew install swiftlint
Xcode에서 적용하기
Target → Build Phases → Run Script 추가
export PATH="$PATH:/opt/homebrew/bin"
if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi
프로젝트 루트에 .swiftlint.yml 파일 추가
#
# https://github.com/google/iosched-ios/blob/master/Source/.swiftlint.yml
# google의 iosched lint
#
disabled_rules:
- line_length
- statement_position
- force_cast
- unused_setter_value
- notification_center_detachment
- large_tuple
- cyclomatic_complexity
- multiple_closures_with_trailing_closure
opt_in_rules:
- file_header
included:
- IOSched
- IOschedTests
- IOschedUITests
excluded:
- IOSched/Common/GeneratedAssets
force_cast: warning # implicitly
force_try:
severity: warning # explicitly
line_length: 110
function_body_length:
warning: 120
error: 400
type_body_length:
warning: 500
error: 1200
file_length:
warning: 900
error: 1600
type_name:
min_length: 3
max_length:
warning: 40
error: 50
variable_name:
min_length: 3
excluded: # excluded via string array
- id
- URL
- url
- x
- y
- i
- j
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, junit, html, emoji)
file_header:
required_pattern: |
\/\/
\/\/ Copyright \(c\) 201[6-9] Google Inc.
\/\/
\/\/ Licensed under the Apache License, Version 2.0 \(the "License"\);
\/\/ you may not use this file except in compliance with the License.
\/\/ You may obtain a copy of the License at
\/\/
\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0
\/\/
\/\/ Unless required by applicable law or agreed to in writing, software
\/\/ distributed under the License is distributed on an "AS IS" BASIS,
\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\/\/ See the License for the specific language governing permissions and
\/\/ limitations under the License.
\/\/
SwiftLint Default Rules (기본 규칙) 번역 및 설명
코딩 스타일 관련 규칙
- attribute_name_spacing: 속성 이름과 콜론(:) 사이의 공백 검사
- blanket_disable_command: SwiftLint의 disable 명령이 광범위하게 적용되는 것을 방지
- block_based_kvo: KVO(Key-Value Observing)에서 블록 기반 API를 사용할 것을 권장
- class_delegate_protocol: delegate 프로토콜이 class 전용인지 확인
- closing_brace: 닫는 중괄호(}) 앞뒤 공백 검사
- closure_parameter_position: 클로저 매개변수 위치 검사
- colon: 콜론(:) 앞뒤 공백 검사
- comma: 쉼표(,) 앞뒤 공백 검사
- comment_spacing: 주석(//) 앞뒤 공백 검사
- compiler_protocol_init: 컴파일러가 생성한 프로토콜 초기화 메서드 감지
- computed_accessors_order: 연산 프로퍼티(get, set) 순서 검사
- control_statement: if, guard, while 등의 제어문 스타일 검사
- custom_rules: 사용자가 정의한 커스텀 규칙 적용
코드 품질 및 복잡도 관련 규칙
- cyclomatic_complexity: 사이클로매틱 복잡도 검사 (높을수록 코드가 복잡함)
- deployment_target: 설정된 최소 배포 대상(Deployment Target)이 일관적인지 확인
- discouraged_direct_init: 특정 클래스의 직접 초기화 금지 (UIColor(), UIFont() 등)
- duplicate_conditions: 중복된 조건문 검사 (if a == 1 && a == 1)
- duplicate_enum_cases: 중복된 열거형(Enum) 케이스 검사
- duplicate_imports: 중복된 import 문 감지
- duplicated_key_in_dictionary_literal: 딕셔너리에서 동일한 키가 중복되는지 검사
- dynamic_inline: @inline(__always)가 불필요하게 사용되었는지 검사
불필요한 코드 관련 규칙
- empty_enum_arguments: 열거형에서 빈 매개변수 검사 (case example())
- empty_parameters: 함수 매개변수가 비어 있는 경우 검사
- empty_parentheses_with_trailing_closure: 후행 클로저 사용 시 빈 괄호 검사
- file_length: 파일 길이(라인 수) 제한
- for_where: for-in 루프에서 where 절을 사용할 것을 권장 (for x in array where x > 5)
- force_cast: 강제 형변환 (as!) 사용 금지
- force_try: 강제 try! 사용 금지
- function_body_length: 함수 본문 길이 제한
- function_parameter_count: 함수 매개변수 개수 제한
- generic_type_name: 제네릭 타입의 네이밍 규칙 검사
네이밍 관련 규칙
- identifier_name: 변수 및 함수 이름 스타일 검사
- implicit_getter: 연산 프로퍼티에서 get 키워드 생략 가능 여부 검사
- inclusive_language: 포괄적이지 않은 언어 사용 제한
- invalid_swiftlint_command: 잘못된 SwiftLint 명령 사용 감지
- is_disjoint: isDisjoint(with:) 사용 권장 (!arrayA.contains { arrayB.contains($0) } 대신 사용)
- large_tuple: 너무 큰 튜플 사용 제한 ((Int, Int, Int, Int, Int) 대신 구조체 추천)
- leading_whitespace: 줄의 시작 부분에 불필요한 공백이 있는지 검사
레거시 코드 관련 규칙
- legacy_cggeometry_functions: CGRectMake, CGPointMake 등의 레거시 함수 사용 금지
- legacy_constant: M_PI 대신 Double.pi 사용 권장
- legacy_constructor: Objective-C 스타일 생성자 (NSDate()) 사용 금지
- legacy_hashing: Swift 4 이전의 해시 함수 사용 금지
- legacy_nsgeometry_functions: NSMakeRect, NSMakePoint 등의 사용 금지
- legacy_random: arc4random 대신 Int.random(in:) 사용 권장
가독성 및 정렬 관련 규칙
- line_length: 한 줄의 최대 길이 제한
- mark: // MARK: 주석 스타일 검사
- multiple_closures_with_trailing_closure: 여러 클로저를 포함한 함수 호출 시 후행 클로저 사용 제한
- nesting: 중첩된 타입, 함수, 제어 구조의 깊이를 제한
제어 흐름 관련 규칙
- no_fallthrough_only: fallthrough만 있는 case 금지
- no_space_in_method_call: 메서드 호출에서 공백 제한 (object .method() 금지)
- non_optional_string_data_conversion: String -> Data 변환 시 옵셔널 제한
- notification_center_detachment: NotificationCenter 옵저버를 올바르게 해제했는지 검사
- ns_number_init_as_function_reference: NSNumber(value:) 대신 NSNumber() 사용 금지
- nsobject_prefer_isequal: NSObject의 == 비교 대신 isEqual(_:) 사용 권장
- opening_brace: { 위치 검사 (func test() { vs func test()\n{)
- operator_whitespace: 연산자(+, -, *, /) 앞뒤 공백 검사
- optional_data_string_conversion: Data -> String 변환 시 옵셔널 제한
- orphaned_doc_comment: 문서 주석(/** ... */)이 특정 코드와 연결되지 않은 경우 경고
코드 최적화 및 리팩토링 관련 규칙
- prefer_type_checking: 특정 타입 체크 방식을 권장
- private_over_fileprivate: fileprivate 대신 private 사용 권장
- private_unit_test: 테스트 함수가 private인지 검사
- protocol_property_accessors_order: 프로토콜 프로퍼티의 get/set 순서 검사
- reduce_boolean: reduce(true, &&) 같은 불필요한 reduce 연산 제한
- redundant_discardable_let: let _ = 같은 불필요한 코드 제한
- redundant_objc_attribute: 불필요한 @objc 속성 제한
- redundant_optional_initialization: 불필요한 옵셔널 초기화 제한 (var name: String? = nil)
- redundant_sendable: 불필요한 Sendable 속성 제한
- redundant_set_access_control: 불필요한 setter 접근 제어자 제한
- redundant_string_enum_value: 열거형에서 불필요한 문자열 값 제한 (enum Example: String { case one = "one" })
- redundant_void_return: 불필요한 Void 반환 제한 (func test() -> Void {})
기타 코드 정리 관련 규칙
- return_arrow_whitespace: -> 앞뒤 공백 검사
- self_in_property_initialization: 프로퍼티 초기화에서 self 사용 제한 (self.value = value 대신 value = value)
- shorthand_operator: 축약 연산자 (+=, -=) 사용 권장
- statement_position: 코드 내 문장 배치 스타일 검사
- static_over_final_class: final class에서는 static 사용 권장
- superfluous_disable_command: 불필요한 swiftlint:disable 제한
- switch_case_alignment: switch 문에서 case 정렬 검사
- syntactic_sugar: 축약된 문법 사용 권장
- todo: TODO: 주석 감지
- trailing_comma: 리스트 마지막 쉼표 검사
- trailing_newline: 파일 끝 공백 줄 검사
- trailing_semicolon: 세미콜론(;) 검사
- trailing_whitespace: 줄 끝 공백 검사
- type_body_length: 클래스, 구조체, 열거형 본문 길이 제한
- type_name: 타입 이름 검사
- void_return: 불필요한 Void 반환 제한
- xctfail_message: XCTFail() 사용 시 메시지 포함 요구
접근성 관련 규칙
- accessibility_label_for_image: UIImageView에 accessibilityLabel이 있는지 검사
- accessibility_trait_for_button: UIButton에 accessibilityTraits가 설정되었는지 검사
코딩 스타일 관련 규칙
- anonymous_argument_in_multiline_closure: 여러 줄 클로저에서 익명 인자($0, $1) 사용 제한
- array_init: 배열을 Array<Type>() 대신 [Type]()으로 초기화 권장
- async_without_await: async 함수에서 await을 사용하지 않는 경우 경고
- attributes: 속성(@objc, @available 등) 배치 스타일 검사
- balanced_xctest_lifecycle: XCTest의 setUp() 및 tearDown() 균형 검사
- closure_body_length: 클로저 본문의 최대 길이 제한
- closure_end_indentation: 클로저 끝나는 위치의 들여쓰기 검사
- closure_spacing: 클로저 { ... } 내부 공백 스타일 검사
- collection_alignment: 컬렉션 요소 정렬 스타일 검사
- comma_inheritance: 클래스 상속 시 콤마(,) 앞뒤 공백 검사
- conditional_returns_on_newline: 조건문에서 return을 새로운 줄에 배치 권장
최적화 및 가독성 관련 규칙
- contains_over_filter_count: filter.count > 0 대신 contains() 사용 권장
- contains_over_filter_is_empty: filter.isEmpty 대신 contains() 사용 권장
- contains_over_first_not_nil: first(where:) != nil 대신 contains() 사용 권장
- contains_over_range_nil_comparison: range != nil 대신 contains() 사용 권장
- contrasted_opening_brace: { 앞뒤 스타일 검사
- convenience_type: convenience init의 적절한 사용 검사
- direct_return: 불필요한 중간 변수 없이 직접 return 사용 권장
- discarded_notification_center_observer: NotificationCenter 옵저버 제거 여부 검사
불필요한 코드 제한 규칙
- discouraged_assert: assert() 대신 precondition() 사용 권장
- discouraged_none_name: none이라는 이름 사용 제한
- discouraged_object_literal: UIColor(named:) 대신 .red, .blue 같은 색상 리터럴 사용 제한
- discouraged_optional_boolean: Bool? 타입 사용 제한 (true 또는 false를 명확히 지정 권장)
- discouraged_optional_collection: Array?, Dictionary? 등의 옵셔널 사용 제한
빈 값 검사
- empty_collection_literal: 빈 배열 [], 빈 딕셔너리 [:] 사용 제한
- empty_count: count == 0 대신 isEmpty 사용 권장
- empty_string: ""을 비교할 때 isEmpty 사용 권장
- empty_xctest_method: XCTestCase에서 내용이 없는 테스트 메서드 감지
열거형 관련 규칙
- enum_case_associated_values_count: 열거형 케이스에서 연관 값 개수 제한
- sorted_enum_cases: 열거형 케이스를 알파벳 순으로 정렬 권장
문서화 관련 규칙
- expiring_todo: TODO: 주석에 만료 기한이 포함되었는지 검사
- explicit_acl: 명시적 접근 제어자(public, private 등) 사용 권장
- explicit_enum_raw_value: enum의 원시 값 명시적 정의 권장
- explicit_init: init()이 명확히 정의되었는지 검사
- explicit_top_level_acl: 최상위 선언(class, struct)에 접근 제어자 명시 요구
- explicit_type_interface: 변수 및 프로퍼티 타입을 명시적으로 선언 권장
- extension_access_modifier: extension에 접근 제어자 명시 요구
제어 흐름 관련 규칙
- fallthrough: switch 문에서 fallthrough 사용 제한
- fatal_error_message: fatalError()에 메시지를 포함하도록 강제
- file_header: 파일 헤더(Copyright 정보 등) 포함 여부 검사
- file_name: 파일 이름 스타일 검사
- file_name_no_space: 파일 이름에서 공백 사용 제한
- file_types_order: 파일 내 코드 배치 순서 검사
- final_test_case: XCTestCase 클래스에 final 사용 권장
- first_where: filter().first 대신 first(where:) 사용 권장
- flatmap_over_map_reduce: map().reduce() 대신 flatMap() 사용 권장
옵셔널 및 강제 언래핑 관련 규칙
- force_unwrapping: ! 강제 언래핑 제한
- function_default_parameter_at_end: 기본값이 있는 매개변수는 마지막에 위치하도록 강제
- ibinspectable_in_extension: @IBInspectable을 확장에서 사용 제한
- identical_operands: 동일한 피연산자로 비교 연산 금지 (a == a 같은 코드)
- implicit_return: return 생략 가능 여부 검사 (-> Void 함수에서 return 생략 가능)
- implicitly_unwrapped_optional: !를 사용한 암시적 옵셔널 제한
코드 정렬 및 스타일 관련 규칙
- indentation_width: 들여쓰기 크기 검사
- joined_default_parameter: joined(separator: "") 대신 .joined() 사용 권장
- last_where: reversed().first(where:) 대신 last(where:) 사용 권장
- legacy_multiple: CGFloat(M_PI * 2) 같은 오래된 코드 스타일 제한
- legacy_objc_type: NSString, NSArray 등의 Objective-C 타입 사용 제한
- let_var_whitespace: let, var 선언 시 공백 스타일 검사
- literal_expression_end_indentation: 리터럴 표현식 끝나는 부분 들여쓰기 검사
- local_doc_comment: 로컬 문서화 주석(///, /** */) 위치 검사
불필요한 코드 제거 규칙
- lower_acl_than_parent: 부모보다 더 낮은 접근 수준(private) 제한
- missing_docs: 문서화 주석(///)이 빠진 경우 감지
- modifier_order: 접근 제어자 및 키워드(static, final 등) 순서 검사
- multiline_arguments: 여러 줄 인수 정렬 검사
- multiline_parameters: 여러 줄 매개변수 정렬 검사
- nimble_operator: XCTAssert 대신 Nimble 사용 권장
테스트 및 예외 처리 관련 규칙
- test_case_accessibility: 테스트 메서드 접근 제어자 검사
- toggle_bool: isOn = !isOn 같은 코드에서 toggle() 사용 권장
- trailing_closure: 후행 클로저 스타일 검사
- type_contents_order: 타입 내 선언 순서 검사
Analyzer Rules (분석 규칙)
- capture_variable: 클로저에서 캡처한 변수가 적절한지 검사
- explicit_self: self 사용 여부 검사
- typesafe_array_init: 배열 초기화 시 타입 안정성 검사
- unused_declaration: 사용되지 않는 함수, 변수, 클래스 감지
- unused_import: 사용되지 않는 import 감지
Rule Directory Reference
realm.github.io
'🍏 > Xcode' 카테고리의 다른 글
[iOS] 코드베이스 프로젝트 세팅 / Codebase Project (0) | 2024.12.30 |
---|---|
[Xcode Cloud] 토이프로젝트에 CI / CD 적용하기 (1) | 2024.11.11 |
[Xcode / Swift] 빌드 시스템에 대한 이해 / 증분 빌드 / 병렬 처리 / Eager Linking / Incremental (1) | 2024.10.29 |
[Tuist+Fastlane+GithubAction] App 배포 CI/CD 과정 (0) | 2024.04.28 |
[Tuist] Version 4 / config / package / dependencies (0) | 2024.03.29 |