이 페이지는 아직 한국어로 제공되지 않습니다. 번역 작업 중입니다. 현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.
Metadata
ID:swift-code-style/closure-max-lines
Language: Swift
Severity: Notice
Category: Code Style
Description
Closures are designed to be a concise way of injecting behavior without defining a separate function. However, when a closure grows beyond a few lines, it becomes harder to read and maintain. Large closures reduce clarity and make the code less adaptable. To keep the source clean and understandable, closures should remain short, and more complex logic should be extracted into dedicated functions.
Arguments
max-lines: Maximum number of lines allowed in a closure. Default: 40.
Non-Compliant Code Examples
// A list of numbers to process.letnumbers=[1,2,3,4,5,6,7,8,9,10]// NON-COMPLIANT: The closure passed to `forEach` is too long and complex.// It mixes data transformation, filtering, and printing, harming readability.numbers.forEach{numberin// 1. First, let's double the numberletdoubled=number*2print("Processing \(number)...")// 2. Check if the doubled number is a multiple of fourifdoubled.isMultiple(of:4){// 3. Now, let's perform a more complex check// Imagine some business logic hereletisSpecialCase=(doubled+number)%3==0ifisSpecialCase{print("Found a special case for \(number)!")}print("Final doubled value is \(doubled)")}else{print("\(doubled) is not a multiple of 4.")}}
Compliant Code Examples
importFoundationletnumbers=[1,2,3,4,5,6,7,8,9,10]/// Processes a single number with all the required business logic./// By moving the logic here, we make it testable and reusable.funcprocessNumber(_number:Int){letdoubled=number*2print("Processing \(number)...")ifdoubled.isMultiple(of:4){letisSpecialCase=(doubled+number)%3==0ifisSpecialCase{print("Found a special case for \(number)!")}print("Final doubled value is \(doubled)")}else{print("\(doubled) is not a multiple of 4.")}}// COMPLIANT: The closure is now a simple, one-line call// to a well-named function. The code is readable and maintainable.numbers.forEach(processNumber)// An alternative compliant example using a trailing closure syntax:numbers.forEach{numberinprocessNumber(number)}
원활한 통합. Datadog Code Security를 경험해 보세요
Datadog Code Security
이 규칙을 사용해 Datadog Code Security로 코드를 분석하세요
규칙 사용 방법
1
2
rulesets:- swift-code-style # Rules to enforce Swift code style.
리포지토리 루트에 위의 내용을 포함하는 static-analysis.datadog.yml을 만듭니다
무료 IDE 플러그인을 사용하거나 CI 파이프라인에 Code Security 검사를 추가합니다