Today we'll check out a library called AwesomeCache by Alexander Schuch that caches data in-memory and on disk. Let's do it.

AwesomeCache can be interacted with in a few different ways. Let's start by creating a cache:

let cache = try! Cache<NSString>(name: "photos")

We can store values in the cache like this:

  forKey: "a-unique-cache-key",
  expires: .Seconds(300)

If we're not setting an expiration time, we can use this shorthand:

cache["a-unique-cache-key"] = "Hello"

We can retrieve values from the cache in a similar way:

let cachedResponse = cache["photos.all"]

One of the handiest features of AwesomeCache is how it can help cache API responses (or any async code really). Here's how it works:

cache.setObjectForKey("photos.all", cacheBlock: { success, failure in
  self.requestLatestPhotos({ response in
    success(response, .Seconds(300))
  }, failure: { error in
}, completion: { object, isLoadedFromCache, error in
  if let object = object {
    // object is now cached, and ready to use

If a value already exists in the cache for the given key, the completion** closure** is called right away. Otherwise, the cacheBlock closure is called. Inside the cacheBlock we call our custom own API code, then tell AwesomeCache if we succeeded or failed.

More info about AwesomeCache can be found at