在本文中,您將學(xué)習(xí)Swift中的嵌套函數(shù)及其如何與示例一起使用。
如果一個(gè)函數(shù)存在于另一個(gè)函數(shù)的主體內(nèi),則稱為嵌套函數(shù)。
func funcname() { //外部函數(shù)語句 func anotherFuncname() { //內(nèi)部函數(shù)語句 } }
在此,函數(shù) anotherFuncname 位于另一個(gè)函數(shù) funcname 的主體內(nèi)部。
應(yīng)當(dāng)注意,內(nèi)部函數(shù)只能在封閉函數(shù)(外部函數(shù))內(nèi)部調(diào)用和使用。
func outputMessageByGreeting(_ message: String) { func addGreetingAndPrint() { print("Hello! \(message)") } addGreetingAndPrint() } outputMessageByGreeting("Jack")
運(yùn)行該程序時(shí),輸出為:
Hello! Jack
在上面的程序中,從封閉函數(shù) outputMessageByGreeting ()調(diào)用了嵌套函數(shù) addGreetingAndPrint ()。
語句 outputMessageByGreeting("Jack") 調(diào)用外部函數(shù)。 外部函數(shù)內(nèi)的語句 addGreetingAndPrint()調(diào)用輸出 Hello Jack!
您不能在函數(shù) outputMessageByGreeting 之外調(diào)用函數(shù) addGreetingAndPrint。
嵌套函數(shù)可以包含帶有參數(shù)和返回值的函數(shù)。
func operate(with symbol:String) -> (Int, Int) -> Int { func add(num1:Int, num2:Int) -> Int { return num1 + num2 } func subtract(num1:Int, num2:Int) -> Int { return num1 - num2 } let operation = (symbol == "+") ? add : subtract return operation } let operation = operate(with: "+") let result = operation(2, 3) print(result)
運(yùn)行該程序時(shí),輸出為:
5
在上面的程序中,
外部函數(shù)為operate(),返回值為Function類型 (Int,Int) -> Int。
內(nèi)部(嵌套)函數(shù)為 add() 和 subtract()。
嵌套函數(shù)add()和subtract()的方式正在使用的封閉函數(shù)的外面operate()。這是可行的,因?yàn)橥獠亢瘮?shù)返回這些函數(shù)之一。
我們已經(jīng)將封閉函數(shù)operate()之外的內(nèi)部函數(shù)用作operation(2,3)。 程序內(nèi)部調(diào)用add(2,3),在控制臺(tái)中輸出5。