Profile Image

2022.10.01.

클로저(Closer)

TIL / Swift

클로저(Closer)

클로저 표현 문법

{(params) -> returnType in
  statements
}

클로저는 이름이 없는(익명) 함수이다. 함수의 파라미터로 전달하는 함수인 콜백함수이다.


클로저의 여러 형태

// 타입 추론
executeClosure(param: {(str: String) in
  return str.count
})
executeClosure(param: {str in
  return str.count
})

// 한줄인 경우 리턴을 생략(Implicit return)
executeClosure(param: {str in
  $0.count
})

// Algument label 생략
executeClosure(param: {
  $0.count
})

// 후행클로저
executeClosure() {
  $0.count
})
executeClosure { $0.count }

후행 클로저 (Trailing closure)

func printTextWithClosure(closure: () -> Void) {
  print("first")
  closure()
}

printTextWithClosure(closure: ) {
  print("second")
}

printTextWithClosure() {
  print("second")
}

printTextWithClosure {
  print("second")
}

함수의 마지막 파라미터로 클로저를 받는 경우 소괄호와 Algument label을 생략 가능하다.


Multiple Trailing closure

func multipleClosure(first: () -> (), second: () -> (), third: () -> ()) {
  first()
  second()
  third()
}

// 기존 문법
multipleClosure(first: {
  print(1)
}, second: {
  print(2)
}) {
  print(3)
}

// 여러개의 클로저를 사용할때 더 간소화된 문법으로 사용 가능
multipleClosure {
  print(1)
} second: {
  print(2)
} third: {
  print(3)
}

Copyright © 2022 HHJ