Swift 嵌套函数
在本教程中,我们将通过示例了解 Swift 中的嵌套函数。
在 Swift 中,函数可以存在于另一个函数的主体中。这称为嵌套函数。
在学习嵌套函数之前,请确保了解 Swift 函数。
嵌套函数的语法
下面是我们如何在 swift 中创建嵌套函数。
// outer functionfunc function1() {// code// inner functionfunc function2() {// code}}
这里,函数 function2() 嵌套在外部函数 function1() 中。
实例:嵌套函数
// outer functionfunc greetMessage() {// inner functionfunc displayName() {print("Good Morning Abraham!")}// calling inner functiondisplayName()}// calling outer functiongreetMessage()
结果为:
Good Morning Abraham!
在上面的示例中,我们创建了两个函数:
greetMessage() - 常规函数
displayName() - 嵌套在 greetMessage() 中的内部函数
这里,我们从外部函数调用内部函数 displayName()。
注意:如果我们试图从外部函数的外部调用内部函数,我们将得到错误消息:use of unresolved identifier。
实例 2: 带参数的嵌套函数
// outer functionfunc addNumbers() {print("Addition")// inner functionfunc display(num1: Int, num2: Int) {print("5 + 10 =", num1 + num2)}// calling inner function with two valuesdisplay(num1: 5, num2: 10)}// calling outer functionaddNumbers()
结果如下:
Addition5 + 10 = 15
在上面的示例中,函数 display() 嵌套在函数 addNumbers() 中。注意内部函数,
func display(num1: Int, num2: Int) {...}
这里,它由两个参数 num1 和 num2 组成。因此,我们在调用它时 display(num1: 5, num2: 10) 传递了 5 和 10。
实例 3:带返回值的嵌套函数
func operate(symbol: String) -> (Int, Int) -> Int {// inner function to add two numbersfunc add(num1:Int, num2:Int) -> Int {return num1 + num2}// inner function to subtract two numbersfunc subtract(num1:Int, num2:Int) -> Int {return num1 - num2}let operation = (symbol == "+") ? add : subtractreturn operation}let operation = operate(symbol: "+")let result = operation(8, 3)print("Result:", result)
结果为:
Result: 11
在上面的实例中,函数 add() 和 substract() 嵌套在 operate() 函数中,
func operate(symbol: String) -> (Int, Int) -> Int {...}
这里,返回类型 (Int, Int) -> Int 指定外部函数返回一个具有
两个 Int 类型的参数和
Int 类型的返回值。
因为这与内部函数的函数定义相匹配,所以外部函数返回一个内部函数。
这就是为什么我们能够从外部函数的外部调用内部函数以及使用
let result = operation(8, 3)
这里,根据传递给 operate() 函数的符号值,用 add(8, 3) 或 subtract(8, 3) 替换 operation(8, 3)。