Updated for Xcode 14.2
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:
previousValue
.newNumber
to store a new random number.repeat
loop with Int.random(in: 1...3)
.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:
previousNumber
, so Swift’s keeping it alive ensures the closure functions as intended.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/
SPONSORED Build a functional Twitter clone using APIs and SwiftUI with Stream's 7-part tutorial series. In just four days, learn how to create your own Twitter using Stream Chat, Algolia, 100ms, Mux, and RevenueCat.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.