Escaping closure 라는 개념은 closure가 함수 외부에 있는 경우를 의미한다.
함수 내에서 필요한 closure가 함수 내부에서 구현되어있는것이 아닌, 외부에서 작성되어 매개변수로 전달되는 경우이다.
@escaping 키워드를 붙여 명시하고 주로 completion 함수를 넘겨줄 때 사용하게된다.
func animate(btn1Y: CGFloat, btn2Y: CGFloat, btn3Y: CGFloat, duration: TimeInterval,
completion: @escaping () -> Void) {
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.5, options: .curveEaseOut) {
self.btn1CenterY.constant = btn1Y
self.btn2CenterY.constant = btn2Y
self.btn3CenterY.constant = btn3Y
// 화면 갱신 꼭 필요
self.view.layoutIfNeeded()
} completion: { _ in completion() }
}
상황에 맞는 UIView animation을 발생시킬 수 있는 함수이다.
animation 효과 이후 실행할 completion 함수를 closure 형태의 매개변수로 받는다.
@IBAction func dimissFloating(_ sender: Any) {
animate(btn1Y: 0, btn2Y: 0, btn3Y: 0, duration: 0.5)
// animate 함수의 completion 구현부
{
self.dismiss(animated: false, completion: nil)
}
}
animation 효과 이후 현재 화면을 dimiss 시키는 함수이다.
위에 구현한 animate 함수 실행 후 사용할 completion 함수를 선언하여 넘겨주었다.
이 때 closure는 animate 함수가 호출되는 위치에서 작성되어 넘겨지기 때문에 이를 사용하는 animate 함수는 escaping closure를 사용하는 것이다.