-
(Swift) the concept of capturing (capturing 개념)iOS💖 2024. 10. 16. 16:57
Closure 는 정의된 주변 context에서 상수/변수를 capture 할 수 있다.
capture 하면, Closure 는 capture 한 상수/변수가 정의 된 범위가 더이상 존재하지 않더라도, 클로저 자신의 본문 내부에서 해당 상수/변수의 값을 참조하고, 수정할 수 있다.
Swift 에서 값을 capture 할 수 있는 가장 간단한 형태의 Closure는, 중첩함수이다.
이게 무슨말인지는,
공식 문서의 예제 코드와, 어떤 문맥에서 'capture' 를 글로 표현하는지 봐보자!
예를 들면, 아래의 코드에서와 같이 이중 함수인 incrementer() 함수 내에서 주변 함수(makeIncrementer)에서
runningTotal 과 amount 에 대한 '참조'를 capture 하여 incrementer() 자체 함수 내에서 사용하여 수행한다.
- ➡️ '참초'로 'capture' 하면, makeIncrementer 호출이 끝날 때, runningTotal 과 amount 가 사라지지 않고, increaser() 함수가 호출 될 때, runningTotal 을 사용할 수 있다.
- makeIncrementer의 반환 유형은 () -> Int이다.
즉, 간단한 값이 아니라 함수를 반환한다는 의미이다.- ➡️함수를 반환한다는 것은, 함수를 참조한다는 말이다.
- 아래의 코드에서, 생성된 makeIncrementer instance 인 incrementByTen 은 incrementer() 함수를 참조하게 된다.
- 따라서, incrementByTen() 을 명령할 때 마다, incrementer() 함수를 호출하게 되는 것이고, Int 값 리턴은 incrementer() 함수가 하게 되는 것이다.
- == incrementByTen() ➡️ incrementer() ➡️ Int 값 리턴
- 아래의 코드에서, 생성된 makeIncrementer instance 인 incrementByTen 은 incrementer() 함수를 참조하게 된다.
- ➡️함수를 반환한다는 것은, 함수를 참조한다는 말이다.
func makeIncrementer(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 func incrementer() -> Int { runningTotal += amount return runningTotal } return incrementer // makeIncrementer의 반환 유형은 () -> Int이다. // 즉, 간단한 값이 아니라 함수를 반환한다는 의미 } let incrementByTen = makeIncrementer(forIncrement: 10) incrementByTen() // returns a value of 10 incrementByTen() // returns a value of 20 incrementByTen() // returns a value of 30 let incrementBySeven = makeIncrementer(forIncrement: 7) incrementBySeven() // returns a value of 7 incrementByTen() // returns a value of 40Function Types as Parameter Types
Documentation
docs.swift.org
Capturing Values
Documentation
docs.swift.org
'iOS💖' 카테고리의 다른 글
[Swift] Network connect 두 가지 방법 (0) 2024.10.22 (Swift) closure @escaping (1) 2024.10.16 (Swift) 메모리 참조 속성 (strong, week, unowned, optional unowned) (3) 2024.10.16 (Swift) ARC (Automatic Reference Counting, 자동 참조 계산) (1) 2024.10.15 (Swift) Result<Success, Failure> 타입 (1) 2024.10.14