Blog School of Programming Swift Closures

Swift Closures

This post on Swift Closures is a continuation of our previous post on Swift functions where we went over the basics of Swift functions.  Let’s get into it!

What is a closure?

A closure can be thought of as a self-contained block of code, typically a function, that uses references from its surroundings. The difference between a function and a closure is that a function needs to be declared as func whereas a closure does not. Closures use scoping, allowing its inner function to have access to its outer function scope.

What is scoping?

Let’s create a variable called myName and place it outside and inside the function getName.

func getName() {
    var myName:String = "Christina"
    print("This is myName inside the function: " + myName)
}


var myName:String = "Zen"
var scopedName = getName()


print("This is myName outside the function: " + myName)
print(scopedName)

Can you guess what the result will be? Will myName change, or will it remain the same?

Output
This is myName inside the function: Christina
This is myName outside the function: Zen

A scope in programming is the concept of where values and functions can be accessed and available within a program. Notice how our variable myName changes based on the scope it has. The variable myName within the function is a local variable with local scope and is limited for use within its code block, while the myName outside of the function is a global variable with global scope that can be used throughout the entire program.

How do closures fit into this? A closure is an enclosed block of code that is able to access references to variables in its outer scope, maintaining connections to its outer environment.

How do I write a Swift closure?

Let’s write our first Swift closure! I want to create a function within another function that is able to access references from my outer function.  What does that look like?
If you look at the Swift documentation, this is the Swift closure structure:

{ (parameters) -> returnType in
  statements
}
Here’s how to write a closure:
let outerSpace = { 
    var phrase = "What a lovely day!"
    func innerSpace(){
        print(phrase)
    }
    innerSpace() 
}
outerSpace()
Output
What a lovely day!

Notice how our inner function is able to access our outer function’s variable phrase since the outer scope “encloses” the scope of the inner function.  This is how closures work.

When do you use a Swift closure?

Closures are useful for several reasons:

  • Reduce or remove redundancy in your code
  • Provide more compartmentalized or modular code
  • Data privacy by creating private variables and functions
  • Ability to customize a function based on certain parameters or arguments
  • Create “memory” by keeping a record in your code that can be called upon for use later

A further look at Swift Closures

Let’s go a little deeper. What if we wanted to pass in a Swift closure as a parameter?  Maybe we want to have an initial phrase be fixed while the second utterance be whatever we want to pass in?  This is an example of customizing your function.

Here’s an example of a Swift closure passed in as a parameter:

//Define function and pass in the closure as a parameter
func outerSpace(innerSpace: ()->()) {
  var phrase = "Greetings!"
  print(phrase)

//Calling the closure
  innerSpace()
}

//Putting it all together
outerSpace(innerSpace: {print("Take me to your leader")})

Output

Greetings!
Take me to your leader

In this example, we are able to provide a default “Greetings!” phrase while the second phase will be up to us what we want to put into our closure.

And, there you have it! A further discussion of Swift functions post with Swift closures. Happy coding!

Want to learn more about Swift? Explore Udacity’s Become an iOS Developer Nanodegree program today!


Glossary

  • Function –  is a piece of code that does something
  • Closure –  a self-contained block of code, typically a function, that holds code and uses references from its surroundings
  • Scope –  the concept of where values and functions can be accessed and available within a program
  • Local variable – a variable that is only accessible within a code block
  • Local scope – can only access values and functions within its code block
  • Global variable – a variable that can be assessed outside or inside any code block within a program
  • Global scope – values and functions that is available anywhere within a program

References

Stay updated on the latest in technology

"*" indicates required fields

Stay updated on the Latest in Tech

Be first to hear about special offers, news, and resources from Udacity

"*" indicates required fields