클로저의 캡처(Capture)
클로저의 가장 큰 특징 중 하나는 외부 변수나 상수를 캡처(Capture)할 수 있다는 점이다. 이는 클로저가 정의된 문맥(Context) 내의 변수들을 클로저 내부에서 참조할 수 있게 해준다.
값 캡처(Value Capture)
값 캡처는 클로저가 외부 변수의 값을 캡처하여 자신의 내부에서 그 값을 사용하는 방식이다. 캡처된 값은 클로저가 생성될 때의 값으로 고정된다. 즉, 클로저가 캡처한 변수는 클로저가 생성된 시점의 값을 갖게 된다.
func makeIncrementer(incrementAmount: Int) -> () -> Int {
var total = 0
let incrementer: () -> Int = {
total += incrementAmount
return total
}
return incrementer
}
let incrementByTwo = makeIncrementer(incrementAmount: 2)
print(incrementByTwo()) // 출력: 2
print(incrementByTwo()) // 출력: 4
print(incrementByTwo()) // 출력: 6
위 코드에서 incrementAmount는 값으로 캡처된다. 클로저 incrementer는 incrementAmount의 값을 클로저가 생성될 때의 값으로 고정하여 사용한다.
참조 캡처(Reference Capture)
참조 캡처는 클로저가 외부 변수의 참조를 캡처하여 자신의 내부에서 그 변수를 참조하는 방식이다. 이는 클로저가 생성된 후에도 외부 변수의 변경 사항을 반영할 수 있게 해준다.
func makeIncrementer() -> (Int) -> Int {
var total = 0
let incrementer: (Int) -> Int = { incrementAmount in
total += incrementAmount
return total
}
return incrementer
}
let increment = makeIncrementer()
print(increment(2)) // 출력: 2
print(increment(3)) // 출력: 5
print(increment(5)) // 출력: 10
위 코드에서 total은 참조로 캡처된다. 클로저 incrementer는 total 변수의 참조를 캡처하여, 클로저 내부에서 total의 값을 변경할 수 있다.