Swift Capturing Value: Adventure in Fibonacci Number of Dynamic Programming

Tsungyu Yu
1 min readJul 8, 2019

--

Photo by Timothy Dykes on Unsplash

This an advanced topic about the Fibonacci number, by using Dynamic programming, we can reduce duplicate operation in the previous number, so that we can make it more efficient.

Fibonacci number

This a correct way to implement fibonacci, but it keep calculus some value that already computed.

Capturing Value:

So, that came to my mind about keeping data. Some people use a variable like Dictionary but didn’t encapsulate anything.

First of all, we need the meat of Fibonacci.

But it just a function, did not keep any data. That why we need a factory to make a capturable closure.

That’s it, we successfully generate a closure.

Keep an eye on the value of operation count.

It will remember the data, and no one can touch the sequence except the function itself.

Make sure you did read it clear, if don’t, feel free to ask.

--

--