ios - Struggling to understand why "Capturing by reference ensures that runningTotal and amount do not disappear when the call to makeIncrementer ends'? -
i'm new swift , trying learn concept of capturing values. saw "the swift programming language 2.1":
func makeincrementer(forincrement amount: int) -> () -> int { var runningtotal = 0 func incrementer() -> int { runningtotal += amount return runningtotal } return incrementer } let incrementbyten = makeincrement(forincrement: 10) incrementbyten()
“the incrementer() function doesn’t have parameters, , yet refers runningtotal , amount within function body. capturing reference runningtotal , amount surrounding function , using them within own function body. capturing reference ensures runningtotal , amount not disappear when call makeincrementer ends, , ensures runningtotal available next time incrementer function called.”
forgive me if questions ask sounds simple or silly of you, been troubling me lot.
q1. why "capture reference can ensure runningtotal , amount not disappear when call makeincrementer ends"?
q2. why "capture reference can ensure runningtotal available next time incrementer function called"?
i'm finding difficult picture , make sense of statements in mind. please me out? in advance help!
swift automatically memory management through arc (automatic reference counting). @ high level, when (strong) reference created against something, counter increases. object won't released memory if reference counter above 0.
so, creating reference (which happens when capture values parent function) you're making sure memory isn't deallocated.
Comments
Post a Comment