November 2016
Intermediate to advanced
480 pages
14h 42m
English
Closures and functions can keep track of internal information encapsulated by a variable defined in their enclosing scope. To see an example of this, imagine that Knowhere is booming. As growth can be erratic, you create a function that will allow you to update the town’s population data based on recent growth. Your town planner will update the town’s census data every time the population grows by 500 people.
Listing 13.11 Tracking growth
...
print("Knowhere has \(stoplights) stoplights.")
func makePopulationTracker(forInitialPopulation population: Int) -> (Int) -> Int {
var totalPopulation = population
func populationTracker(growth: Int) -> Int {
totalPopulation += growth
return totalPopulation
}
return ...Read now
Unlock full access