我在我的代码中犯了一个错误,我认为应该阻止它编译和运行,但事实并非如此。所以我很好奇,为什么这会编译:
func function1() {
print("function1")
func function2() {
print("function2")
}
}
function1() // prints "function1"
答案 0 :(得分:5)
因为Swift支持嵌套函数。
...您还可以在其他函数体内定义函数,称为嵌套函数。
默认情况下,嵌套函数对外界是隐藏的,但它们的封闭函数仍然可以调用它们。封闭函数也可以返回其嵌套函数之一,以允许嵌套函数在另一个范围内使用。
它们有很多用途,但一个常见的用例是定义一个公共函数,它使用嵌套函数通过递归计算结果。例如,作为这种设计的结果,您可以添加一次参数检查(在外部函数中),这样您就不必在每次递归调用时重复检查。
func factorial(_ i: Int) -> Int {
// This check is only done once, rather than with every recursion
print("Checking to verify that i is non-negative")
guard 0 <= i else {
fatalError("Can't compute factorial of the negative number: \(i)")
}
func factorialRecurser(_ i: Int) -> Int {
print("Computing factorial of \(i)")
switch i {
case 0, 1: return 1;
default: return i * factorialRecurser(i - 1)
}
}
return factorialRecurser(i)
}
print(factorial(10))
结果如下:
Checking to verify that i is non-negative
Computing factorial of 10
Computing factorial of 9
Computing factorial of 8
Computing factorial of 7
Computing factorial of 6
Computing factorial of 5
Computing factorial of 4
Computing factorial of 3
Computing factorial of 2
Computing factorial of 1
3628800
将此与更天真的解决方案进行比较:
func naiveFactorial(_ i: Int) -> Int {
// This check is needlessly repeated
print("Checking to verify that i is non-negative")
guard 0 <= i else {
fatalError("Can't compute factorial of the negative number: \(i)")
}
print("Computing factorial of \(i)")
switch i {
case 0, 1: return 1;
default: return i * naiveFactorial(i - 1)
}
}
print(naiveFactorial(10))
结果如下:
Checking to verify that i is non-negative
Computing factorial of 10
Checking to verify that i is non-negative
Computing factorial of 9
Checking to verify that i is non-negative
Computing factorial of 8
Checking to verify that i is non-negative
Computing factorial of 7
Checking to verify that i is non-negative
Computing factorial of 6
Checking to verify that i is non-negative
Computing factorial of 5
Checking to verify that i is non-negative
Computing factorial of 4
Checking to verify that i is non-negative
Computing factorial of 3
Checking to verify that i is non-negative
Computing factorial of 2
Checking to verify that i is non-negative
Computing factorial of 1
3628800
查看冗余执行非负检查的次数。