This post comes from this tweet shared by David Rodrigues (if you don't follow him on Twitter you should):
If you have a closure that needs some internal state to be used and modified between executions of the closure you can declare your state as part of the capture list, this guarantees your state is only accessed and modified inside your closure as it should. #swiftlang pic.twitter.com/kVKTiQE2zc— David Rodrigues (@dmcrodrigues) July 2, 2018
Initially I got a bit puzzled about it, but I though I recognized a technic I have used before: memoization.
In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again
A lot of the blog posts out there use the Fibonnaci sequence to showcase this technique. Personally, I find it boring, how many times do you need outside interviews? 🤷♀️
Let's build something "useful" 😅
This solution acts as a map from requests to responses. It also provides the extra benefit of allowing a consumer to audit the cache, so you know exactly what is being sent and received by your app!
Using it is as straighforward as:
In contrast, David's solution eliminates some boilerplate and it also hides the
AtomicCache via a capture list (which for some, it might be considered an implementation detail). The same solution using David's approach would look like this:
As previously said, there pros/cons to both approaches. The interesting bit for me is that I had no idea you could create a new entity in a capture list. 🤓