December 2015
Intermediate to advanced
400 pages
13h 3m
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 makeGrowthTracker(forGrowth growth: Int) -> () -> Int {
var totalGrowth = 0
func growthTracker() -> Int {
totalGrowth += growth
return totalGrowth
}
return growthTracker
}
var currentPopulation = 5422
let growBy500 ...Read now
Unlock full access