On this page
1 min read
Every function and block ({
... }
) introduces a new scope for declarations.
Each function and block can refer to declarations in its scope or any of the outer scopes.
1let x = 1023fun f(): Int {4let y = 105return x + y6}78f() // is `20`910// Invalid: the identifier `y` is not in scope.11//12y
1fun doubleAndAddOne(_ n: Int): Int {2fun double(_ x: Int) {3return x * 24}5return double(n) + 16}78// Invalid: the identifier `double` is not in scope.9//10double(1)
Each scope can introduce new declarations, i.e., the outer declaration is shadowed.
1let x = 223fun test(): Int {4let x = 35return x6}78test() // is `3`
Scope is lexical, not dynamic.
1let x = 1023fun f(): Int {4return x5}67fun g(): Int {8let x = 209return f()10}1112g() // is `10`, not `20`
Declarations are not moved to the top of the enclosing function (hoisted).
1let x = 223fun f(): Int {4if x == 0 {5let x = 36return x7}8return x9}10f() // is `2`