클로저가 아직 익숙하지 않아서 함수에서 사용된 후행클로저를 좀 자세히 알고 싶어서 작성합니다.
후행 클로저
함수의 마지막 인수에 클로저 표현식을 전달해야 하고 클로저 표현식이 긴 경우 후행 클로저로 작성하면 가독성이 더 좋아집니다.
func someFunctionThatTakesAClosure(closure: () -> Void) {
// function body goes here
}
// Here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure(closure: {
// closure's body goes here
})
// Here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
자주 사용했던 고차함수 map도 후행클로저로 더 가독성 있게 표현할 수 있습니다.
let num = arr.map{ $0.description }
이는 파라미터로 인자를 받아서 클로저에 실행할 수도 있고, 받지않고 실행할 수 있습니다.
// 인자 없이 후행 클로저
func calculate(_ closure: (Int, Int) -> String ) {
print(closure(10, 20))
}
// 인자를 전달하는 후행클로저
func calculate2(_ num1: Int,_ num2: Int,_ closure: (Int, Int) -> String) {
let result = closure(num1, num2)
}
// 후행 클로저의 구현부는 함수의 호출부에서 구성
calculate { num1, num2 in
return "\(num1 + num2)"
}
calculate2(10, 20) { num1, num2 in
return "\(num1 + num2)"
}
'Swift > 문법' 카테고리의 다른 글
Swift의 타입들 Types (0) | 2025.03.26 |
---|---|
ARC dive deep (0) | 2025.03.21 |
enum의 다른 사용방법 (0) | 2025.03.14 |
Swift Protocols (0) | 2025.03.11 |
Swift 구조체와 클래스 (0) | 2025.02.12 |