[Swift] 탈출 클로저

나는 사과·2021년 2월 20일
0

TIL

목록 보기
2/17

안녕하세요😀
오늘은 Swift하면 빼놓을 수 없는 이야기인 클로저에서 특히!! 탈출 클로저에 대해서 헷갈리는 부분이 있어서 정리하면서 다시 한번 기억해보려고 합니다.

탈출 클로저?

먼저 탈출?? 이라는 단어는 Swift에서 함수의 전달인자로 전달한 클로저가 함수 종료 후에 호출될 경우를 클로저가 함수를 탈출한다 라고 한다.
탈출 클로저를 명시할 때는 클로저를 매개변수로 갖는 함수를 선언할 때 매개변수 이름 콜론(:)뒤에 @escaping키워드를 사용해 명시해준다.

그럼 클로저가 함수를 탈출하는 경우는 어떻게 될까?

책에서는
함수 외부에 정의된 변수 or 상수에 저장되어 함수가 종료된 후 사용할 경우
에 클로저가 함수를 탈출할 수 있는 경우로 소개하고 있다.

typealias VoidVoidClosure = () -> Void

let firstClosure: VoidVoidClosure = {
	print("A Closure")
}

let secondClosure: VoidVoidClosure = {
	print("B Closure")
}

func returnOneClosure(first: @escaping VoidVoidClosure, second: @escaping VoidVoidClosure, shouldReturnFirstClosure: Bool) -> VoidVoidClosure {
	// 이 부분에서 전달받은 first나 second 클로저를 return하기 때문에 탈출 클로저다.
	return shouldReturnFirstClosure ? first : second
}

let returnedClosure: VoidVoidClosure = returnOneClosure(first: firstClosure, second: secondClosure, shouldReturnFirstClosure: true)

returnedClosure() // A Closure 출력

위의 예시에서 returnOneClosure함수가 클로저를 타입별칭으로 생성한 VoidVoidClosure를 매개변수로 전달받으면서 return하기 때문에 이 부분에서 탈출이 일어나게 된다. 그래서 매개변수 앞에 @escaping을 넣어주었다.

그리고 만약, 탈출 클로저임을 명시했을 때 클로저 내부에서 프로퍼티, 메서드, 서브스크립트 등에 접근하려면 꼭! self키워드를 넣어주어야 한다.

0개의 댓글