Notice: Undefined index: understanding-swift in /var/sites/hackingwithswift.com/site/src/Controller/NewBooksReadController.php on line 89
Why do Swift’s closures capture values? - a free tutorial

NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Why do Swift’s closures capture values?

Paul Hudson    @twostraws   

One of the most important features of Swift’s closures is that they capture values they use. At the same time, one of the most confusing features of Swift is that they capture values they use. Put simply, value capturing takes place so that your closure always has access to the data it needs to work, which means Swift can run the closure safely.

As an example, let’s try writing a function that generates random numbers, but with a twist: it won’t return the same number twice in a row.

The logic for this is fairly simple:

  • We’ll start with an initial value of 0, stored in previousValue.
  • We’ll then create a new variable called newNumber to store a new random number.
  • We’ll use a repeat loop with Int.random(in: 1...3).
  • The condition for that loop will be newNumber == previousNumber – keep the loop going around picking new numbers as long as the new random number is the same as the previous random number.

Once the loop finishes it means our number is definitely different from the previous one, so we update previousValue to be newValue, then send it back. Remember, this should be sent back as a closure, so we can generate random numbers from wherever we want.

Here’s how we could write all that:

func makeRandomNumberGenerator() -> () -> Int {
    return {
        var previousNumber = 0
        var newNumber: Int

        repeat {
            newNumber = Int.random(in: 1...3)
        } while newNumber == previousNumber

        previousNumber = newNumber
        return newNumber
    }
}

We can now take that code for a test drive like this:

let generator = makeRandomNumberGenerator()

for _ in 1...10 {
    print(generator())
}

Give it a try! Chances are you’ll see things didn’t quite go to plan – I got numbers repeated several times, e.g. 1, 2, 1, 1, 3, 1, 3, 3, 3, 2.

That wasn’t what we wanted; we wanted no repeating numbers, so what happened?

The problem is here:

return {
    var previousNumber = 0
    var newNumber: Int

That returns the closure we’re calling, which means every time we call generator() it creates a new previousNumber variable set to 0 – it isn’t storing the previous value at all.

Now I want you to move that var previousNumber = 0 line so it comes before the return, like this:

var previousNumber = 0

return {
    var newNumber: Int

If you run the code now, you’ll see it works just as we hoped – we get a new random value each time, but won’t get any repeats.

What you’re seeing here is the power of closure capturing: that previousNumber variable isn’t inside the closure, but because the closure requires it to exist in order to run it will be captured. That is, Swift will make sure it stays in existence even after makeRandomNumberGenerator() has finished running and it would normally have been destroyed.

This matters for two reasons:

  1. If the variable had been destroyed, then our closure wouldn’t be able to work any more. It tries to read and write previousNumber, so Swift’s keeping it alive ensures the closure functions as intended.
  2. Although the variable is used by the closure, it’s created outside the closure. This means it only gets set to 0 once, rather than every time the closure is run, which is why it now stores the previous value correctly.

So, this is a real example of why closuring capturing matters: having an external value makes sure we can track some state outside a closure while using it inside.

Closure capturing is a complicated topic, but if you’d like to read even more about it then check out Olivier Halligon’s post: https://alisoftware.github.io/swift/closures/2016/07/25/closure-capture-1/

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Link copied to your pasteboard.