이 챕터에서 접한 모든 함수는 전역 범위에서 정의된 전역 함수 (global functions) 의 예이다. 중첩 함수 (nested functions) 라고 하는 다른 함수 내에 함수를 정의할 수도 있다.
중첩 함수는 기본적으로 바깥에서 보이지 않지만 중첩 함수를 둘러싼 함수를 통해 호출될 수 있고 사용될 수 있다. 중첩 함수를 둘러싼 함수는 중첩 함수 중 하나를 반환하여 중첩 함수를 다른 범위에서 사용할 수도 있다.
위의 예제 chooseStepFunction(backward:) 를 중첩 함수를 사용하고 반환하도록 다시 작성할 수 있다:
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backward ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
print("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!