클로저는 코드의 블럭입니다.
일급 시민(first-citizen)이기 때문에 변수, 상수 등으로 저장할 수 있고,
전달인자로 전달이 가능합니다.
함수는 클로저의 일종으로, 이름이 있는 클로저라고 생각하시면 됩니다.
{ (매개변수 목록) -> 반환타입 in
실행 코드
}
// 만약 매견변수가 필요없으면 ()만 쓰시고 사용하시면 됩니다.
// 만약 반한타입이 없다면 void를 쓰면 됩니다.
func sumFunction(a: Int, b: Int) -> Int{
return a + b
}
var sumResult: Int = sumFunction(a: 3, b: 2)
print(sumResult) // 5
var sum: (Int, Int) -> Int = { (a: Int, b: Int) in
return a + b
}
sumResult = sum(1, 2)
print(sumResult) // 3
앞서 말했듯이 함수는 클로저의 일종이므로
sum 변수에는 당연히 함수도 할당할 수 있습니다.
sum = sumFunction(a:b:)
sumResult = sum(4,3)
print(sumResult) // 7
// 덧셈
let plus: (Int, Int) -> Int
plus = { (a: Int, b: Int) int in
return a + b
}
// 뺄셈
let minus: (Int, Int) -> Int
minus = { (a: Int, b: Int) -> Int in
return a - b
}
// 곱셈
let multiplication: (Int, Int) -> Int
multiplication = { (a: Int, b: Int) -> Int in
return a * b
}
// 나눗셈
let divide: (Int, Int) -> Int
divide = { (a: Int, b: Int) -> Int in
return a / b
}
// calculate 함수(클로저로 넘겨줌)
func calculate(a: Int, b: Int, method: (Int, Int) -> Int) -> Int {
return method(a, b) // 함수 안에서 전달받은 클로저 호출
}
var calculated: Int
calculated = calculate(a: 50, b: 10, method: add)
print(calculated) // 60
calculated = calculate(a: 50, b: 10, method: minus)
print(calculated) // 40
calculated = calculate(a: 50, b: 10, method: multiplication)
print(calculated) // 500
calculated = calculate(a: 50, b: 10, method: divide)
print(calculated) // 5