- 클로저는 이름없는 함수, 코드 블록을 의미
- 상수나 변수의 참조를 캡쳐해 저장할 수 있다
a. 값 캡쳐 : 변수나 상수의 값을 캡쳐한다. 이 때, 클로저 내부에서 캡쳐한 값이 변경되어도 원본 값은 변경되지 않는다
b. 참조 캡처 : 변수나 상수의 참조를 캡쳐한다. 따라서 클로저 내에서 헤딩 변수나 상수를 변경하면 원본 값도 변경된다// 값 캡처 func makeIncrementer (forIncrement amount: Int) -> () -> Int { var total = 0 let incrementer: () -> Int = { total += amount return total } return incrementer } let incrementByTen = makeIncrementor(forIncrement: 10) print(incrementByTen()) //total = 10, 결과 10 print(incrementByTen()) //total = 20, 결과 20
// 참조 캡처 class SimpleClass { var value: Int = 10 } func createClosure() -> (() -> Int ) { let instance = SimpleClass() let closure: () -> Int = { instance.value *= 2 return instance.value } return closure } let myClosure = createClosure() print(myClosure()) // 20 print(myClosure()) // 40
- 클로저는 클래스와 마찬가지로 참조 타입이다
- 클로저를 사용하는 이유? 기능을 저장하기 위해서
- 코드 축약의 기술
func performClosure(param: (String) -> Int) { param("Swift") } performClosure(param: { (str: String) in return str.count }) // 타입 추론 performClosure(param: { str in return str.count }) // 한 줄인 경우 리턴을 안 적어도 됨 performClosure(param: { str in str.count }) // 아규먼트 이름을 축약 performClosure(param: { $0.count }) // 트레일링 클로저 performClosure() { $0.count } performClosure { $0.count }
개념이 쉽지 않고 한 번에 와닿지 않는다. 여러 번 반복해서 보고 익히자