As mentioned in the inaugural post, the goal of
Swift: Shuffle All (
S:SA henceforth) is to explore the Swift standard library in a random fashion.
At the time, an external source of entropy was used to choose the first topic for discussion. However, as this can’t always be relied on, a more reliable method of harnessing entropy to enable serendipity needs to be found.
The entropy harness that was developed is outlined briefly in the remainder of this post.
Big Nerd Ranch’s Freddy is used rather than
NSJSONSerialization to allow for more fluent JSON parsing. Numerous other options exist, but are beyond the scope of this post.
Fortunately SwiftDoc exposes an API, avoiding reliance on a third-party index.
NSURLSession data task is used to query the endpoint which returns all SwiftDoc entry URLs.
Assuming a good response, this is parsed as JSON and checked for a top-level dictionary containing the name and URL of SwiftDoc entries.
This dictionary is mangled into a dictionary keyed by category and its associated entries — based on the assumption that entry URLs contain their category.
Some categories of limited interest are trimmed (at time of writing these were
404 and operators).
Finally a random category and entry within this category are chosen. This requires some interaction between
arc4random_uniform which returns integers and the opaque index type used by
The result is presented as a string literal (only suitable for REPL or Playground use for the time being).
Finally, the data task is resumed as these are not scheduled for execution automatically.
Having outlined the internals of the entropy harness, upcoming posts will benefit from the fruits of its labour.tags: