大器晩成

트레일링(Trailing)클로저 - 후행클로저 문법 본문

iOS/Swift 문법

트레일링(Trailing)클로저 - 후행클로저 문법

zerobugpark 2025. 2. 25. 16:43

 

[문법 최적화(간소화)]

  • 문맥상에서 파라미터와 리턴 벨류 타입 추론 (Inferring Type Form Context)
  • 싱글 익스프레션인 경우(한 줄) return 키워드 생략 가능 (Implicit Returns from Single-Expression Closures)
  • 아규먼트 이름 축약 (Shorthand Argument Names)  -> $0, $1, $2 등
  • 트레일링 클로저: 함수의 마지막 아규먼트(전달 인자)로 클로저가 전달되는 경우, 소괄호 생략 가능

 

트레일링 클로저

//Apple 공식문서

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
    closure()
}

// Here's how you call this function without using a trailing closure:

someFunctionThatTakesAClosure(closure: {
    // closure's body goes here
    print("클로저 함수 정의")
  
})

// Here's how you call this function with a trailing closure instead:

someFunctionThatTakesAClosure() {
    // trailing closure's body goes here
    print("소괄호 앞으로 가져가기 및 아규먼트 레이블 생략 가능")
}

someFunctionThatTakesAClosure { // 최종형태
    print("소괄호 생략 가능")
}


// 추가 예졔
func sumPrintFunctionClosure(num: Int, num2: Int, closure: (Int) -> ()) {
    let sum = num + num2
    closure(sum)
    
}

//num: Input 파라미터
sumPrintFunctionClosure(num: 10, num2: 20) { num in
    print(num)
}
  • 함수를 실행할 때 클로저 형태로 전달할 수 있습니다.
  • 함수의 마지막 전달 인자로 클로저가 전달되는 경우 소괄호 생략이 가능합니다.

문법 간소화 과정

func helloClosure(closure: (String) -> Int) {
    closure("Hello Swift")
}


// 1. 기본 형태
helloClosure (closure: { (str: String) -> Int in
    return str.count
})

// 2. 반환값 생략
helloClosure (closure: { (str: String) in
    return str.count
})

// 3. 타입 추론에 의한 타입 생략
helloClosure (closure: { str in
    return str.count
})

// 4. 한줄인 경우, 리턴 생략 가능 (Implicit Returns from Single-Expression Closure)
helloClosure (closure: { str in
    str.count
})


// 5. 아규먼트 이름 축약 (Shorthand Argument Names)
helloClosure (closure: {
    $0.count
})

//6. 트레일링 클로저
helloClosure () {
    $0.count
}

helloClosure { $0.count }

 

멀티플 트레일링 클로저 - Swift 5.3

  • 여러 개의 함수를 파라미터로 사용할 때 사용됩니다.
func multipleClosure(square: (Int) -> (), even: (Int) -> (), odd: (Int) -> ()) {
    square(10)
    even(10)
    odd(10)
    
}

// 스위프트 5.3 이전
multipleClosure (square: {
    print($0 * $0)
}, even: {
    print($0 % 2 == 0)
}) {
    print($0 % 2 != 0)
}

// 스위프트 5.3 이후
multipleClosure {
    print($0 * $0)
} even: {
    print($0 % 2 == 0)
} odd: {
    print($0 % 2 != 0)
}

 

참고

//(Int) -> Bool
let even = {
    $0 % 2 == 0
}
// 어떠한 수를 나룰 수 있는건 정수 뿐이기 때문메 Int타입의 ->Bool 반환 타입이 추론 가능


//(Int, Int) -> Int
let multiply: (Int, Int) -> Int = {
    $0 * $1
}
// 곱하기는 Int 타입뿐만 아니라, Double, float 타입에서도 사용이 가능하기 때문에, 타입을 명시
  • 타입 추론이 불가할 때는 타입을 명시해줘야 합니다.
728x90