Swift Generics – Cache

Generics are awesome. In fact, they are insanely cool when it comes to writing reusable code. To demonstrate their usefulness, let’s build a generic Cache storage.

Our cache should meet the following requirements:

  • Should be fast (read, write) – O(1)
  • Support hashable data type (NSData, UIImage, String, Int, etc)
  • Support custom size to allow for initialization based on memory limitations
  • Should keep track and clear out oldest objects before adding new ones
  • Should keep recently accessed data by marking it as the most recent

Before writing code, let’s talk about implementation. For starters, I will use a dictionary to store the actual data. Reason behind using a dictionary (or a hash table) should be rather obvious… both the lookup and insertion of data takes constant time. This will be especially useful when dealing with large cache size.

Continue reading “Swift Generics – Cache”

Swift Generics – Cache