位置:首頁 > 高級語言 > Swift教學 > Swift嵌套函數

Swift嵌套函數

嵌套函數(Nested Functions)

這章中你所見到的所有函數都叫全局函數(global functions),它們定義在全局域中。你也可以把函數定義在彆的函數體中,稱作嵌套函數(nested functions)。

默認情況下,嵌套函數是對外界不可見的,但是可以被他們封閉函數(enclosing function)來調用。一個封閉函數也可以返回它的某一個嵌套函數,使得這個函數可以在其他域中被使用。

你可以用返回嵌套函數的方式重寫 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 now refers to the nested stepForward() function
while currentValue != 0 {
    println("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!