So here is the memoize function in swift:
First of all the function signature is much different because of the pseudo dynamic types in swift. Although variables can be typed at compile time, it will eventually get typed, and once set, it can’t change.
So lets break down the signature.
So the memoize function has a single parameter, a closure that takes an array of Any and returns an Any optional. The reason why it taks an array of Any will be more clear as I go further into the function.
The memoize function will return a closure of type Any variadic that returns an Any optional. The reason why the returned function takes an Any variadic is so that the function can be called with as many parameters as necessary.
For those unfamiliar, variadic parameters allow a function to take an unlimited number of parameters of the given type. So a function with a variadic parameter could be called like
foo(1, 2, 3). All of the parameters will be in an array of the parameter name. For more info on variadic parameters checkout Apples documentation.
So that’s the just of the memoize function. In order to use the function, the closure you write must be a specific type.
Here is an example of a possible function that could be memoized.
Then we would memoize it by passing it to memoize. But because the closure that is returned from memoize is of a different type than the closure we are passing into memoize, we must assign the result to a new variable.
So now if we run memSum:
So there you have it. A memoize function in swift. Although it may not be ideal to write your closures with the required type, it could prove beneficial at some point.