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”
It [Swift 3.0] is inevitable. – Agent Smith
We are getting pretty close to the release of Swift 3.0. Part of me is very excited (fifty percent of me, to be precise). Since a few of my projects are completely written in Swift, no Objective-C, I decided to dive into Swift 3.0 with the release of a toolchain snapshot. I was particularly interested in quantifying the amount of effort it will require to update my apps (I like to migrate my code manually and see new changes rather then using auto-migration tool shipped with Xcode).
Needless to say, my project secretly named “Cobra (think of Jesse from the Burn Notice) – Update to Swift 3.0” wasn’t successful. It is way too early. I still managed to get a simple project setup and got myself familiarized with the new syntax – awesome. By the way, Playgrounds don’t work.
If you are interested, here are simple steps on how to use the Swift 3.0 Preview Toolchain in current version of Xcode (7.3.1).
First of all, head over to www.swift.org and download the latest snapshot (direct link here).
Once downloaded, run the package installer. This will install the new toolchain. Next, you’ll need to go to Xcode / Toolchains and select Swift 3.0 Preview 1 Snapshot. You’ll be asked to restart Xcode…
From here, it is time to test the waters and create a new project. I would suggest starting with a Single View Application template… a couple of warnings and compiler errors later, you are on your way to write your code.
Happy Swift 3.0 writing…
UPDATE: I successfully updated my project to Swift 3.0.