0
我在我的代码中犯了一个错误,我认为应该阻止它编译和运行,但它没有。所以我很好奇,为什么这样编译:为什么编译?在另一个函数中声明的函数
func function1() {
print("function1")
func function2() {
print("function2")
}
}
function1() // prints "function1"
我在我的代码中犯了一个错误,我认为应该阻止它编译和运行,但它没有。所以我很好奇,为什么这样编译:为什么编译?在另一个函数中声明的函数
func function1() {
print("function1")
func function2() {
print("function2")
}
}
function1() // prints "function1"
因为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
看多少次没有正反面检查被重复执行。
感谢您的示例用例。很好的答案! – grez