在 Swift 中,一个函数可以存在于另一个函数的函数体内。这被称为嵌套函数。
在学习嵌套函数之前,请确保您了解Swift 函数。
嵌套函数语法
以下是我们如何在 Swift 中创建嵌套函数。
// outer function
func function1() {
// code
// inner function
func function2() {
// code
}
}
在此,函数 function2()
嵌套在外部函数 function1()
的内部。
示例 1:Swift 嵌套函数
// outer function
func greetMessage() {
// inner function
func displayName() {
print("Good Morning Abraham!")
}
// calling inner function
displayName()
}
// calling outer function
greetMessage()
输出
Good Morning Abraham!
在上面的示例中,我们创建了两个函数:
greetMessage()
- 一个常规函数displayName()
- 一个嵌套在greetMessage()
中的内部函数
在这里,我们从外部函数调用内部函数 displayName()
。
注意:如果我们尝试从外部函数外部调用内部函数,我们将收到错误消息:use of unresolved identifier
(未解析的标识符)。
示例 2:带参数的嵌套函数
// outer function
func addNumbers() {
print("Addition")
// inner function
func display(num1: Int, num2: Int) {
print("5 + 10 =", num1 + num2)
}
// calling inner function with two values
display(num1: 5, num2: 10)
}
// calling outer function
addNumbers()
输出
Addition 5 + 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 numbers
func add(num1:Int, num2:Int) -> Int {
return num1 + num2
}
// inner function to subtract two numbers
func subtract(num1:Int, num2:Int) -> Int {
return num1 - num2
}
let operation = (symbol == "+") ? add : subtract
return operation
}
let operation = operate(symbol: "+")
let result = operation(8, 3)
print("Result:", result)
输出
Result: 11
在上面的示例中,函数 add()
和 subtract()
嵌套在 operate()
函数中。请注意外部函数的声明。
func operate(symbol: String) -> (Int, Int) -> Int {
...
}
在这里,返回类型 (Int, Int) -> Int
指定外部函数返回一个具有以下特征的函数:
- 两个
Int
类型的参数,以及 - 一个
Int
类型的返回值。
由于这与内部函数的函数定义匹配,因此外部函数返回其中一个内部函数。
这就是为什么我们还可以通过以下方式从外部函数外部调用内部函数:
let result = operation(8, 3)
在这里,operation(8, 3)
根据传递给 operate()
函数的 symbol 的值,被替换为 add(8, 3)
或 subtract(8, 3)
。