Este producto no es compatible con el sitio Datadog seleccionado. ().
Esta página aún no está disponible en español. Estamos trabajando en su traducción.
Si tienes alguna pregunta o comentario sobre nuestro actual proyecto de traducción, no dudes en ponerte en contacto con nosotros.

Metadata

ID: swift-code-style/closure-max-lines

Language: Unknown

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.
let numbers = [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 { number in
    // 1. First, let's double the number
    let doubled = number * 2
    print("Processing \(number)...")

    // 2. Check if the doubled number is a multiple of four
    if doubled.isMultiple(of: 4) {
        // 3. Now, let's perform a more complex check
        // Imagine some business logic here
        let isSpecialCase = (doubled + number) % 3 == 0
        
        if isSpecialCase {
             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

import Foundation

let numbers = [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.
func processNumber(_ number: Int) {
    let doubled = number * 2
    print("Processing \(number)...")

    if doubled.isMultiple(of: 4) {
        let isSpecialCase = (doubled + number) % 3 == 0
        if isSpecialCase {
             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 { number in
    processNumber(number)
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Integraciones sin problemas. Prueba Datadog Code Security