標籤:style 使用 strong os io for
Function Types as Return Types (函數類型作為傳回值類型)
一個函數的類型可以作為另一個函數的傳回值類型.可以在一個函數的傳回值箭頭後面寫上一個完整的函數類型.
例如:
下面的例子定義了兩個簡單的函數,分別為stepForward 和 stepBackward.其中stepForward函數傳回值比它的輸入值多1,stepBackward函數傳回值比它輸入值少1.這兩個函數的 類型都是(Int) -> Int:
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
這裡有一個函數chooseStepFunction,它的傳回型別是一個函數類型(Int) -> Int.函數chooseStepFunction根據它的布爾類型的參數返回stepForward函數類型或者stepBackward函 數類型 :
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
現在你可以使用chooseStepFunction獲得一個函數:
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the stepBackward() function
moveNearerToZero將根據適當的函數來計算,一直到零:
println("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
println("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// 3...
// 2...
// 1...
// zero!
Nested Functions (函數嵌套)
你可以在一個函數體內定義另一個函數,這種情況叫做嵌套函數.
預設情況下,嵌套的函數對外界是不知的.但可以通過封裝它的函數來調用它.封裝它的函數可以將它作為函數的傳回值返回,這樣可以允許嵌套的函數在其他範圍使用.
代碼範例:
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!
/********************本章完......************************/