Swift Studies

At WWDC 2014 Apple introduced a new programming language, Swift. At this point everyone has exactly zero days experience in Swift. This blog will capture and share our learning, and I hope the learnings of others as we go.

One of Swift 2's most exciting additions are protocol extensions. These allow you to add new methods to anything that implements a protocol. I thought it might be interesting to explore this with a practical example, generating random or repeating sequences from any collection.

The use-case is quite simple. We have a collection and we would like to either select a certain number of random elements from it, or repeat it up to a certain number. We may like to do either of these, but manage our own stopping condition.

It's now incredibly easy to inject the new methods into a protocol's implementers

The four methods are quite simple (I could have used default parameters to reduce to just two, taking an optional length that defaulted to nil, but the semantics felt wrong. I either want to specify a length, or I don't and that should be obvious to someone reading the code).

So now anything that implements CollectionType will have these methods (The characters of a String, arrays, sets, dictionaries or even something you've implemented yourself).

I will include the implementation of ProxySequence and its associated GeneratorType here, but it's not really the focus of this post so read only if you care!

Swift Studies

Even a simple text adventure contains all of the fundamentals of lexers, parsers, and interpreters. Using STLR to define the grammar, and its Swift code generation, we quickly create a simple adventure game in Swift.