# Lexical scoping in Swift

While going through lexical scoping concept in LISP; I wondered whether such support is available in Swift or not. And it does. Yay…

I took a simple function — *square root of a number* to try out the lexical scoping. I used Newton’s method for calculating square roots. Below is the first version.

sqRt is a recursive function. The code terminates when the guess made in earlier step is good enough. Else guess is improved and function is called again.

But then functions like *goodEnough* and *improveGuess *does not make any sense outside squareRoot function scope. Thankfully in Swift, *functions are first class citizen*. We can declare function just like declaring variable. This brings me to the second version of *sqRt* function.

Functions like *improveGuess*, *goodEnough* are operating on the function parameters of *sqRt*. As these functions are already in the scope of *sqRt* function, one can argue that passing parameters to these inner functions is redundant. Which is indeed true and that’s what is addressed with *lexical scoping*. Parameters/ variables of the enclosing function are in scope for these functions.

A language with LexicalScoping has following characteristics:

1. Functions (and procedures, etc.) can be defined within other functions

2. Such inner functions have access to the local variables defined in the enclosing scope.

3. These inner functions also have an access to the function parameters of the enclosing function.

Version 3 of the *sqRt* function by leveraging lexical scoping support is as follows.

Hey wait! Why can’t we leverage Swift’s support further to concise the code. *Square*, *goodEnough* and *improveGuess* look like variables. So let’s simplify those.

I hope you understood lexical scoping support in Swift. Let me know your thoughts on this.