Closures
Learn how to use closures to define and call higher-order functions.
StartKey Concepts
Review core concepts you need to learn to master this subject
Defining a Closure
Inputs and Outputs
Passing Closures to Functions
Trailing Closure Syntax
Shorthand Argument Names
Common Higher-order Functions
Escaping Closures
Capturing Values
Defining a Closure
Defining a Closure
let displayWelcome = { () -> Void in
print("Hello World!")
}
displayWelcome() // Prints: "Hello World"
Closures are self-contained blocks of functionality. Just like functions, closures take in arguments, execute instructions, and return a value or Void
.
Closures
Lesson 1 of 1
- 1Closures are self-contained chunks of code that are first-class citizens in Swift. This means they can be assigned to variables and passed as arguments to functions. Closures may be referred to as …
- 2Before we define a closure let’s recall the function definition from the Functions module. This will be helpful to reference while we step through the closure definition. func functionName(par…
- 3So far we have defined closures without arguments or return values. Just like with functions, it’s very useful for our closures to be able to accept inputs, perform tasks with the inputs, and retur…
- 4Closures are first-class citizens in Swift. This means they can be assigned to variables and passed as arguments to functions. Now that we’ve looked at assigning them to variables, let’s see how we…
- 5Up until this point we have been fairly explicit about defining the type of the closure, assigning it to a variable, and passing the variable to a function. With Swift being a strongly typed langua…
- 6Because closures are so common in Swift, there are quite a few niceties or “syntactic sugar” that are available to shorten your code. To explain these, let’s take a look at a function that takes a …
- 7A higher order function is a function that takes a closure as input or a functions that returns a closure. This is something we have defined ourselves already in the previous exercises. In this exe…
- 8It is possible for a closure to be called after the function it was passed into returns. This is called an escaping closure and is wrapped with the @escaping keyword. This is common when a functi…
- 9Up until now we have passed parameters into our closures to perform operations on. With closures we can also capture variables and constants outside the scope of the closure. This is known as “clos…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory