1. Swift 3 : Closure
군산대학교 컴퓨터정보통신공학부 컴퓨터정보공학전공
남 광 우
kwnam@kunsan.ac.kr
Swift 3 Tour and Language Guide by Apple
꼼꼼한 재은씨의 Swift 2 프로그래밍
2. Closure
• Closure 란?
• 코드 안 또는 함수 파라미터로 전달되어 사용될 수있
는 self‐contained 블록 { }
• nested function 또는 anonymous function의 특수한 형태
• Java, Python의 Lamda와 동등
• Closure는 정의되는 context상의 상수와 변수들에 대한 레퍼
런스를 capture하고 저장하고 있음
• Closure의 종류
• Global Functions
• Nested Functions
• Closure Expressions
3. • Context 의 capture 및 저장이란?
func basic( param : Int ) ‐> (Int) ‐>Int
{
let value = param + 20;
func append( add: Int) ‐> Int {
return value + add;
}
return append;
}
let b = basic(10) ;
b(20);
b(20)
append() 함수가 수행되기 위해서는
global function인 basic()의
value 상수까지 보관되어야 함
nested function
global function
함수 basic(10) 호출 후 종료
Closure
4. Closure Expressions
• Closure Expression의 형태
• 다음의 syntax를 갖는 self‐contained 블록 { }
• Closure의 예 : Hello Closure~
{ (parameters) ‐> returnType in
statements
}
{ () ‐> () in
print( “ Hello Closure~!”);
}
{ () ‐> Void in
print( “ Hello Closure~!”);
}
9. Closure Expressions : Sort
• 긴 Closure 함수의 외부 표현 방법
func someFunctionThatTakesAClosure(closure: () ‐> Void) {
// function body goes here
}
// Here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure(closure: {
// closure's body goes here
})
// Here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
10. Closure Expressions : Sort
• Trailing Closure : Sort 의 외부 표현
• 외부 표현
• ()의 생략
reversedNames = names.sorted() { $0 > $1 }
reversedNames = names.sorted { $0 > $1 }
11. Closure Expressions
• Trailing Closure 의 예
• 십진수‐>영어로 읽기
• Array의 Map 메소드 구현
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]
let strings = numbers.map {
(number) ‐> String in
var number = number
var output = ""
repeat {
output = digitNames[number % 10]! + output
number /= 10
} while number > 0
return output
}
// strings is inferred to be of type [String]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]
12. Array의 map, filter, reduce
• Map, Filter, and Reduce
• Swift 표준 배열 라이브러리의 Closure 지원 함수
• Map
func map<U>(transform: (T) ‐> U) ‐> Array<U>
4
3
5
6
7
8
6
10
12
14
map{$0*2}
map{$0*2}
map{$0*2}
map{$0*2}
map{$0*2}
let arr = [3, 4, 5, 6, 7]
let doubleArr = arr.map{ $0 * 2 }