Up 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 “closing over” the values that are captured. One example is a nested function. Let’s take a look at a function that keeps track of new friends we make:

func makeFriendAdder() -> (String) -> [String] { var friends = [String]() let addFriend: (String) -> [String] = { name in friends.append(name) return friends } return addFriend }

We have defined a function named makeFriendAdder that returns a closure that accepts a String and returns a String array. In the function’s body, we declare a variable named friends which is the array that will hold our friends. After that, we define a closure named addFriend with the same function return type. The closure closes over the friends array to add the name that is passed to the block. Finally we return the block.

let friendAdder = makeFriendAdder() friendAdder("Jake") print(friendAdder("Kate")) // prints ["Jake", "Kate"]

The reason this is possible is because closures in Swift are reference types. When we assign the closure to the friendAdder constant we are creating a reference to the closure which has captured the friends array.

Also, with type inference, we can clean up the implementation a bit:

func makeFriendAdder() -> (String) -> [String] { var friends = [String]() return { name in friends.append(name) return friends } }

The function return type matches the type of the closure we are returning so we can omit the type declarations.



Define a function named createMultiplier that accepts an integer named factor and returns a closure with type () -> Int


Within the function, declare a variable named value of type Intinitialized with a value of 1. Then, declare a closure named multiplier that closes over value, multiplies it by factor, and is returned. Then, return the multiplier closure to the closing function.


Create a closure from the createMultiplier function with a value of 3 and assign it to a variable named multiplier. What is the value after calling multiplier() 3 times?

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?