この章でここまでに見た関数はすべて、グローバルスコープで定義されたグローバル関数の例です。ネストされた関数として、別の関数の本体に関数を定義することもできます。
ネストされた関数は、外側の世界からデフォルトでは隠れていますが、ネストしている関数では呼び出して使用することができます。ネストされた関数を別のスコープで使用できるように、ネストしている関数からネストされた関数を返すこともできます。
上で見た chooseStepFunction(_:)
の例を書き換えて、ネストされた関数を返して使用することができます。
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backwards ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero はネストされた関数 stepForward() を参照
while currentValue != 0 {
print("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.