-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
클로저(Closure)란?
코드에서 전달되고 사용될 수 있는 자체적인(self - contained)함수 블록
- 람다 함수와 유사
- 클래스와 동일한 참조 타입
기존 함수와 클로저 함수 비교
func aFunction(str: String) -> String {
return "Hello, \(str)"
}let _ = {(str: String) -> String in
return "Hello, \(str)"
}클로저 함수 형태
{ (매개변수 목록) -> 반환 타입 in
실행 코드
}ex) a와 b를 더하는 함수
let _ = {(a: Int, b: Int) -> Int in
let result = a + b
return result
}클로저(Closure) 생략
- 반환, 인자 타입 생략
타입을 아는 경우 타입 생략 가능
let closure1 = {a, b in
let result = a + b
return result
}- 반환 키워드 생략
단일 표현 클로저는 반환 키워드 생략 가능
let closure2: (Int, Int) -> Int = { a, b in
a + b
}- 인자 이름 축약 (Shorthand Arguments Names)
클로저의 매개변수 이름이 굳이 필요 없다면 단축 인자를 활용 가능하다.
let closure3: (Int, Int) -> Int = { $0 + $1 }- 연산자 메소드(Operator Methods)
let closure4: (Int, Int) -> Int = (+)Reactions are currently unavailable