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