함수의 Input에 함수를 넣을 수 있습니다. 아래의 calculator 함수의 Input을 보면 operation: (Int, Int) -> Int처럼 함수가 인자로 들어간 것을 확인 할 수 있습니다.
(Int, Int) -> Int 처럼 정의를 하면 (Int, Int) -> Int 형식의 Input과 Return 형식을 가진 모든 함수를 인자값으로 넣을 수 있습니다.
그리고 calculator 함수의 return 값으로 operation(no1, no2)가 있는 것을 볼 수 있는데, 인자로 넣어준 Int값 두 개를(no1, no2) 인자로 넣어준 함수에(operation) 인자로 넣어 계산한 함수의 리턴값을 다시 리턴하는 구조입니다.
func calculator(no1: Int, no2: Int, operation: (Int, Int) -> Int) -> Int {
return operation(no1, no2)
}
func add(no1: Int, no2: Int) -> Int {
return no1 + no2
}
func subtraction(no1: Int, no2: Int) -> Int {
return no1 - no2
}
func multiply(no1: Int, no2: Int) -> Int {
return no1 * no2
}
func divide(no1: Int, no2: Int) -> Int {
return no1 / no2
}
calculator(no1: 5, no2: 5, operation: add) // 10
calculator(no1: 5, no2: 5, operation: subtraction) // 0
calculator(no1: 5, no2: 5, operation: multiply) // 25
calculator(no1: 5, no2: 5, operation: divide) // 1
Closure
closure를 간단히 설명하자면 함수를 편리하게 사용하기 위해 함수의 모습을 간략화한 일련의 코드블럭이라고 말 할 수 있습니다.
위의 예시에서 사용한 함수를 가져와 Closure 형태로 구현해 보겠습니다.
calculator(no1: Int, no2: Int, operation: (Int, Int) -> Int) -> Int {
return operation(no1, no2)
}
// add 함수의 원형
func add(no1: Int, no2: Int) -> Int {
return no1 + no2
}
// operation의 인자값으로 add 함수의 클로저를 입력. func 키워드와 함수명을 생략
calulator(no1: 5, no2: 5, {(no1: Int, no2: Int) -> Int in
return no1 + no2
})
// 타입 추론 이용
calulator(no1: 5, no2: 5, {(no1, no2) in
return no1 + no2
})
// return 생략
calulator(no1: 5, no2: 5, {(no1, no2) in no1 + no2})
// $이용
calulator(no1: 5, no2: 5, {$0 + $1})
// 트레일링 클로져(trailing closure
calulator(no1: 5, no2: 5) {$0 + $1}
'Swift' 카테고리의 다른 글
Swift - Extension (0) | 2020.01.14 |
---|---|
Swift - Double형 데이터를 String으로 포멧 지정하여 나타내는 법 (0) | 2020.01.10 |
Swift - Delegate Design Pattern의 초보적 이해 (0) | 2019.12.09 |
Swift - String을 Float으로 캐스팅 하는 법 (0) | 2019.12.06 |
Swift - 옵셔널 (0) | 2019.12.06 |