Swift Code:
func makeIncrementor(forIncrement amount: Int) -> (() -> Int,() -> Int) { var runningTotal = 0 func incrementor() -> Int { runningTotal += amount return runningTotal } func decrementor()->Int{ runningTotal -= amount return runningTotal } runningTotal += 1000; return (incrementor,decrementor) } let counter = makeIncrementor(forIncrement: 1); let a1 = counter.0(); assert(a1==1001, "a1") let a2 = counter.0(); assert(a2==1002, "a2") let a3 = counter.0(); assert(a3==1003, "a3") let c1 = counter.1(); assert(c1==1002, "c1")
Objective-C Code:
__block int runningTotal = 0; int (^incrementor)() = ^(){ return ++runningTotal; }; int (^decrementor)() = ^(){ return --runningTotal; }; runningTotal=1000; int a1 = incrementor(); int a2 = incrementor(); int a3 = incrementor(); int c1 = decrementor();