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

Melissa Hong

Recent Posts

Udacity Unveils a Completely Revamped iOS Developer Nanodegree Program

Announcing iOS Development with SwiftUI and SwiftData The demand for iOS developers proficient in Swift…

6 days ago

Unlocking Dreams in Tech: Christopher Sledd’s Journey with the OneTen/BIT Scholarship

In a world driven by technology, finding the right opportunity to break into the tech…

1 week ago

AWS and Udacity Surpass $24 Million Worth of AI Programming Scholarships Awarded to Underserved Students in Less Than Three Years

This month, more than 1,000 people received notifications of their free enrollment in the AI…

2 weeks ago

6 Free Courses: Become A Google Cloud Digital Leader

Developers & IT Pros are harnessing the power of Google Cloud to solve real-world problems.…

2 weeks ago

New Course: Build the Future on Hedera

From Weekend Projects to Web3's Next Big Thing Ready to help shape the future of…

3 weeks ago

How Do I Become A Programmer? The 7-Step Guide

It might be obvious by now, but here at Udacity, we really love tech and…

3 weeks ago