Closures Are Reference Types

Closures are reference types. This means that when you assign a function to a constant or variable you are actually setting that constant or variable to point to the function. You are not creating a distinct copy of that function. One important consequence of this fact is that any information captured by the function’s scope will be changed if you call the function via a new constant or variable.

To see this, create a new constant and set it equal to your growBy500() function.

Listing 13.13  Duplicate growth

... func makeGrowthTracker(forGrowth growth: Int) -> () -> Int { var totalGrowth = 0 func growthTracker() -> Int { totalGrowth += growth return totalGrowth } return growthTracker } var currentPopulation ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.