Swift ErrorTypes – A Modest Proposal

After the WWDC announcement, when I got over my initial knee-jerk ‘Exceptions – ick!’ reaction, I came around to being a supporter of the Swift 2 error handling model. While it would be nice to be able to desugar the implicit result type, and there’s a glaringly obvious hole with async error handling, for general failable synchronous calls it works well. However, there’s one aspect that really bothers me. Consider the following code:

enum MathError: ErrorType {
    case DivideByZeroError

func divide(l: Int, _ r: Int) throws -> Int {
    guard r != 0 else { throw MathError.DivideByZeroError }
    return l / r

func calculate() {
    do {
        let result = try divide(10, 2)
        print("Result = \(result)")
    } catch MathError.DivideByZeroError {
        print("Can’t divide by zero!")
    } catch {
        // this should never happen

Errors thrown by a function are completely untyped, so Swift is unable to infer that the first catch clause is exhaustive – this means you ALWAYS have to include a catch-all at the end of your do block if you want to completely handle the error. This isn’t just a case of redundant code – if you add an error case later on, you’re going to suddenly (and silently) hit your ‘This should never happen’ handler, which is probably not what you’d expect (and seems out of step with the way switch statements work).

The other problem is that we have no idea from the function signature what errors we should be trying to catch. Apple introduced a Throws: keyword in the doc comments, but relying on the original developer to keep comments up to date can be… ineffective.

A number of people have proposed that throwing functions should be declared with a list of all the types they can throw, rather like Java’s checked exceptions. This will nicely solve our divide function example:

func divide(l: Int, _ r: Int) throws MathError -> Int {
    guard r != 0 else { throw MathError.DivideByZeroError }
    return l / r

func calculate() {
    do {
        let result = try divide(10, 2)
        print("Result = \(result)")
    } catch MathError.DivideByZeroError { // this catch is exhaustive
        print("Can’t divide by zero!")

Which is great – we now have a sensible exhaustive catch statement, we’ll get helpful compile errors if we add a MathError case and forget to handle it, and the function definition is clearer and self-documenting. However, this is a fairly simple case, and the problems with checked exceptions were always much more evident with larger & more modular codebases – for instance, we’d start to see functions like:

func openDatabase(path: String) throws libuvError, URLFormatError, ZipArchiveError, SQLiteError -> Database {

Technically in this case we’d still be able to write an exhaustive catch without using a catch-all, but I can give a rock-solid guarantee that no-one ever will. A function signature like this leaks internal implementation details, and the exposed error types are very unlikely to be useful to API consumers.

Additionally, this can have an invasive impact on the rest of the code – consider the scenario where these error types are annotated on all functions that call openDatabase, then all the functions that call those functions, and so-on up the line until we have a monster catch (all) block. Now imagine we update our database code and add a new ErrorType, or change the zip library and that ErrorType is now different. We could end up having to touch a dozen files to cover a semantically unimportant change. It’s also worth noting that the Swift team have explicitly said they don’t want “pedantic lists of possible error types, like Java”.

Now this is a somewhat pathological case (although I have seen a lot of Java code written like this in the past!) and hopefully ‘good developers’ wouldn’t write code this way. The way this problem should be solved would be either:

  1. Erase the typed error information that’s not useful to consumers and just throw an untyped ErrorType – this brings us back full-circle – or
  2. Translate the internal errors into a meaningful new ErrorType, such as:
enum DatabaseError: ErrorType {
    case InvalidPath(message: String)
    case CorruptDatabase(message: String)

Ultimately, the more I’ve thought about this, the less useful a list of multiple ErrorTypes seems to be. However, I think there’s still value in being able to (optionally) annotate a single custom ErrorType, as in the case of the MathError or a consolidated DatabaseError from our openDatabase call. So my Modest Proposal is stated thus:

// allow us to do this:
func myFunction() throws -> Int

// or this:
func myFunction() throws CustomError -> Int

// but not this:
func myFunction() throws CustomErrorOne, CustomErrorTwo -> Int

A single custom ErrorType is much closer to the underlying language model, neatly complements the Swift 2.1 function covariance, delivers most of the benefits of typed errors, and limits the damage that slovenly error propagation can do to the codebase.

Using Xcode Playgrounds for Presentations

Playground Presentation

Playgrounds are primarily designed as a learning tool, but with Xcode 7’s multiple pages and expanded rich markup support, they’re also really great for presentations – they allow you to mix slide-like text & image content with interactive code (for coding demos). Because everyone loves coding demos!

I used this technique last week at /dev/world/2015, and thought I’d share a few tips if you’re interested in doing your own playground presentations.

  1. Don’t try to put too much content on the one page; otherwise you’ll spend half the presentation scrolling up & down.
  2. Add a key binding to the ‘Show Rendered Markup’ menu option – you’ll be using it a lot!
  3. Use the image markup (//: ![[Alt Text]](image_name.jpg)) to show images from your ‘Resources’ folder – e.g. diagrams you’d normally put on a slide.
  4. Don’t use a dark text theme if you’ll be presenting on a projector – a light theme will be more readable. Also, don’t forget to change the Console font size in your presentation theme!
  5. Use custom Xcode snippets rather than typing in code – it’s much quicker & less error-prone, but your audience will still feel like the code is coming together in front of them. Another option is to pre-fill most of the code and just add the interesting bits live.
  6. If you’re using a Swift file in ‘Sources’ to hide supporting code, note that types must be public to be visible to the playground.
  7. Swift code in ‘Sources’ can’t link to custom frameworks, so you’ll need to put your supporting code in a separate framework if you want to do this. ‘Sources’ is best used for basic helper functions.
  8. Implementing CustomPlaygroundQuickLookable on your types can add a lot of fun to your presentation if it’s something that lends itself to a visual.

Lastly, be prepared for the playground to crash (because it will!)

My /dev/world talk is available online if you’d like to see the playground presentation in action.

AWS Powershell: “A parameter cannot be found that matches parameter name ‘Credentials’.”

I spent ages debugging this one a few months ago, and just hit it again, so I thought I’d share to save others some time.

If you have an older AWS powershell script, you may hit this error when running AWS Powershell cmdlets, particularly if using a cross-account role – e.g.:

$aws_role = Use-STSRole -RoleArn $arn -ExternalId $externalid -Region $region
$aws_creds = $aws_role.Credentials

Get-S3Bucket -Credentials $aws_creds -BucketName $bucket -Region $region
# will throw "A parameter cannot be found that matches parameter name 'Credentials'."

The problem is that at some point, the AWS Powershell cmdlets renamed the ‘Credentials’ parameter to ‘Credential’ (no trailing s). Running the script after upgrading AWS Powershell manifests the error. To compound this, I assume because of the way they’ve implemented the shared parameters, Get-Help doesn’t actually show the Credential parameter at all. I trawled through the release notes and was unable to find the version at which the parameter changed, or even if there was any warning.

The fix is obviously to rename your -Credentials parameters to -Credential, and then shake your fist in the general direction of Amazon.

“Principles of Reactive Programming” course review

I recently completed the “Principles of Reactive Programming” course on Coursera – I’m very interested in FRP (and libraries like ReactiveCocoa) as I find a lot of the most painful bugs in the iOS code I work on relate to using mutable flags/timestamps (or application state) to coordinate multiple event callbacks. I’m positive there’s a better way, and I suspect FRP is it. On paper, this course looks the goods – it follows on from Odersky’s highly-regarded “Functional Programming Principles in Scala” course, and includes material from three thought-leaders of the FRP world – Martin Odersky (Scala Futures & Promises), Erik Meijer (Rx), and Roland Kuhn (Akka/Actor Model). It’s a 7 week course, run using Scala as the assessment language and main vehicle for the concepts, with  a very cool automated code submission/grading system. Firstly, the good:

  • Setup of the environment was relatively painless. I used IntelliJ rather than Eclipse (because who would ever willingly install Eclipse?), and aside from the typical OS X JRE/JDK hoops, and a minor import problem in Week 3, it worked flawlessly.
  • The content was really top-notch – the video lectures were comprehensive, well-paced, and well-presented by people who knew their stuff.
  • The submission and grading worked quite well. Once you’d completed the coding assignment, you just run the sbt target submit and your code was compiled, packaged and submitted. On the server, an automated process ran unit tests against the submission, and posted a grade & output from the failed tests online within about 5 minutes.

Aspects that I found irritating/frustrating were:

  • I hadn’t used Scala before and spent a good 60% of my time trying to work out how to perform basic tasks. Obviously the recommendation is to do Odersky’s Scala course first, but the description claimed knowledge of general functional programming concepts would be sufficient (I believe this has now been changed).
  • The course structure, with three different presenters teaching three different programming models, felt a bit disjointed – it could easily be split into three separate courses. The different models weren’t really brought together for meaningful comparison.
  • There were a few quirks with the grading system – the downloaded projects did not always include all of the grading tests, and in some cases the local tests were pretty minimal and didn’t assist much in writing the correct code. This made development pretty slow unless you could reverse-engineer the failing test. I also came across a case where the tests broke code written in a certain way – this was perhaps unavoidable, but there were a bunch of confused people on the forums who were getting no response or clarification from TAs.

Ultimately though, I learnt a lot (which would be the main measure of success). I’d comfortably recommend the course to anyone who already knows Scala, but I’d love to see a CLR version of the course in C# or F# covering the TPL, Rx.NET and Akka.NET. In the iOS world there’s also a desperate need for good learning material covering ReactiveCocoa 3 and a few of the other Swift async libraries (PromiseKit etc).

Watch App Development Blog – Week 6

 I’m blogging my progress in developing an Apple Watch App. Read the previous instalments here.

Telstra – grrr!

I had a frustrating week trying to track down an odd issue – I wouldn’t get any train times load when I was walking around (i.e. near the station, where I want to test), but there was nothing showing up in the logs. The app would work perfectly at home when plugged into Xcode. This put a bit of a dampener on the planned Pebble app field testing. Eventually I managed to log an error message (NSURLErrorDomain -1003 – hostname not found). It turns out the tutum.io subdomain assigned to my docker endpoint isn’t resolving on any of Telstra’s DNS servers. I’m running Google DNS at home, which resolves the hostname fine, and so doesn’t exhibit the issue, but on 4G I’m at the mercy of the Telstra DNS. After an hour on the phone with Telstra, this has been ‘escalated to Level 3 support’ and I’ll get a response ‘within 7 days’. I’ve switched back to an IP address so I can continue my testing.

What did we learn here?

While I’m obviously shocked that Telstra’s internet services could be anything less than spectacular, the key takeaway is that leaving logging out of your code DOESN’T SAVE TIME. Swift makes it trivially easy to return a typesafe, idiot-proof error result that forces you to think critically about how you’re managed error conditions in your code. Consider this snippet (the culprit):

func get<T: JSONConvertible>(path: String, f: [T] ->()) {
    Alamofire.request(.GET, hostname + path)
        .responseJSON { (_, _, json, _) in
        if let json = json as? [NSDictionary] {
            f(json.map({ T(dictionary: $0) }))
        } else {

func getAllStations(f: [Station] -> ()) {
    get("/train", f)
  1. I’m ignoring the error object that Alamofire is helpfully returning (the last parameter in responseJSON)
  2. I’m returning an empty array if literally anything goes wrong. Networking error, HTTP error (like a 500 from the server), malformed JSON payload, the lot = empty array.

In this case the empty station array was overwriting the locally cached stations, and my ‘nearestStation’ method was never producing a result. Because it’s just refreshing a local cache of fairly static data, I can safely ignore errors if I already have data. This could be done by testing the array count in the callback, but we should be able to do better.

Let’s change our ApiClient get method to the following:

enum Result<T> {
    case Value(Box<T>)
    case Error(NSError)

func get<T: JSONConvertible>(path: String, f: Result<[T]> ->()) {
    Alamofire.request(.GET, hostname + path)
        .responseJSON { (_, _, json, error) in
        if let json = json as? [NSDictionary] {
            f(Result.Value(Box(json.map({ T(dictionary: $0) }))))
        } else if let error = error {
        } else {
            f(Result.Error(NSError(domain: ApiClientErrorDomain,
                code: 1,
                userInfo: [NSLocalizedDescriptionKey: "An unknown error occurred."])))

We’re defining a Result type that returns either the requested value, or an NSError. Ignore the Box, this is only a figment of your imagination, and is totally not a hack to work around the Swift compiler’s problems with ‘non-fixed multi-payload enum layouts’. Note I’m also creating an ‘unknown error’ to handle the case where I don’t get back an error object from Alamofire. Just in case.

I use the updated API as follows:

        getAllStations { r in
            switch r {
            case let .Value(s):
            case let .Error(e):
                println("Error refreshing stations from the server: \(e.localizedDescription)")

So we have glorious logging in case of error and a rather annoying ‘unbox’ call. Importantly though, due to the signature of the API, it’s now much harder to lazily ignore error handling.

Watch App Development Blog – Week 4 *cough* 5

 I’m blogging my progress in developing an Apple Watch App. Read the previous instalments here.

So, um, I missed a week. Sorry about that. Sad face.

Step 4: The Pebble

We don’t have access to any Apple Watch hardware yet, so it’s difficult to get a good feel for how you will use your app in context. I was given a Pebble for Christmas though, and thought it may be worthwhile getting the core information displayed on a Pebble app so I can experience and analyse the usage flow behind a watch app with this data.

Pebble: the Palm Pilot of Smartwatches

First, my impressions of the pebble:

  • Battery life is not too bad, I get about a week of normal usage. It doesn’t compare favourably to several years of battery life on a traditional watch (like my trusty Tag 2000), but it should soundly spank most newer-generation smart watches, including the Apple Watch, based on the rumours to date.
  • The screen is awful if you’re used to a high-resolution smartphone display. The B&W 144 x 168 display looks like 90s tech.
  • The Watch itself is plasticky (lasted a whole day before it copped a small but visible scratch on the face), and too large and ungainly for most wrists.
  • The app/watchface marketplace is fairly limited & most of the apps have a ‘hobbyist’ feel to them. I don’t necessarily mean that in a negative manner – it’s great to see the enthusiasm, but without a good mechanism to monetise apps there’s not the same level of investment & innovation that I see in the iOS App Store or the Play Store.
  • The hardware is fairly slow and anaemic.
  • Development for the pebble is difficult. The Pebble C API is very low level, requires a lot of careful memory management, can only run on the device, and can’t be debugged. They’ve released a JavaScript API to try to make the experience a bit better, though I haven’t tried it.
  • If you’re using your pebble with an iPhone, the experience is less than seamless due to Apple’s bluetooth accessory restrictions. Some functionality  (e.g. network access) stops working if the Pebble iOS app has been terminated from the background. Third party iOS apps have a single Pebble connection to share, and communication can only be initiated from the phone.

To me, the product is very reminiscent of the early Palm Pilots – clunky B&W screen, an awkward developer experience, small hobbyist developer community etc. The future’s yet to be written, but the Pebble will need to undergo radical and ruthless improvement to keep pace with the latest smartwatches.

The Pebble App

The general concept behind the watch app is a simple display showing the departure times for the closest station. This should provide the ‘in context’ component of the most important watch app functionality. The initial UI design (pictured) includes the nearest station, and the destination, pattern, and minutes remaining for the next four departures from the station.

Pebble Mockup

The simplest way to manage communication between the phone app & the watch app is the AppSync API. The general semantics of the API involve syncing a dictionary of shared data between the phone & watch; it also makes data storage on the watch more convenient. The downside is that this requires a specific key for each individual data element synced to the watch – i.e. specific numbered departures rather than a variable array of scheduled trains.

With that in mind, the keys were defined thus:

#define KEY_STATION 0
#define KEY_DEST_1 1
#define KEY_TIME_1 2
#define KEY_DEST_2 3
#define KEY_TIME_2 4
#define KEY_DEST_3 5
#define KEY_TIME_3 6
#define KEY_DEST_4 7
#define KEY_TIME_4 8

The main issue I ran into with AppSync was a storage limitation. The sample code includes a 30 byte sync buffer which is insufficient for most data sync requirements, but it wasn’t immediately obvious that’s what the error DICT_NOT_ENOUGH_STORAGE was referring to. Upping the buffer to 128 bytes solved the issue. That should be enough for anybody.

Once the data was synced, I update the UI using the following function:

static void drawText() {
  const Tuple *tuple;
  if ((tuple = app_sync_get(&s_sync, KEY_STATION))) {
    if (tuple->value->cstring[0] == 0) {
      text_layer_set_text(station_text_layer, "Waiting for data");
    } else {
      text_layer_set_text(station_text_layer, tuple->value->cstring);
  for (int i = 0; i < 4; i++) {
    if ((tuple = app_sync_get(&s_sync, i * 2 + 1))) {
      if (tuple->value->cstring[0] == 0) {
        text_layer_set_text(dest_text_layers[i], "");
      } else {
        text_layer_set_text(dest_text_layers[i], tuple->value->cstring);
    if ((tuple = app_sync_get(&s_sync, i * 2 + 2))) {
      if (!tuple->value->int32) {
        text_layer_set_text(time_text_layers[i], "");
      } else {
        time_t departure_time = tuple->value->int32;
        time_t current_time = time(NULL);
        int minutes = (departure_time - current_time)/60;
        char time_str[5];
        snprintf(time_str, 5, "%dm", minutes);
        text_layer_set_text(time_text_layers[i], time_str);

…where dest_text_layers and time_text_layers are four element arrays containing references to the text layers on the watch UI.

Can you spot the bug? If you haven’t done much work with embedded systems it’s not obvious. Critically, the documentation for text_layer_set_text says:

The string is not copied, so its buffer most likely cannot be stack allocated, but is recommended to be a buffer that is long-lived, at least as long as the TextLayer is part of a visible Layer hierarchy.

time_str is not copied when passed to text_layer_set_text; the effect being that it goes out of scope and is never displayed on the watch face. The solution is a set of string buffers referenced statically – I used a static char pointer array, and malloced/freed the buffers in window_load/window_unload.

// at the top of the file
static char *time_strings[4];

// in the window_load() function
  for (int i = 0; i < 4; i++) {
    time_strings[i] = malloc(sizeof(char[TIME_LABEL_LENGTH]));

// drawtext() changes to:
  snprintf(time_strings[i], TIME_LABEL_LENGTH, "%dm", minutes);
  text_layer_set_text(time_text_layers[i], time_strings[i]);

The iOS App

Pebble integration doesn’t require a a substantial amount of code – drag in the frameworks and pull a PBWatch reference from PBPebbleCentral.defaultCentral().lastConnectedWatch(). Because I want to be able to show the number of minutes until a train leaves, I changed the earlier code from a HH:MM string to a ZonedDate/NSDate in the Haskell & Swift code. I then implemented Pebble communication using the following (dest/pattern is abbreviated to economise on transfer bandwidth & Pebble display size):

    func updatePebble(station: Station, _ times : [Departure]) {
        var pebbleUpdate : [NSNumber: AnyObject] = [
            KeyStation : station.name,
        for i: Int in 0..<4 {
            let destKey = NSNumber(int: Int32(i * 2 + 1))
            let timeKey = NSNumber(int: Int32(i * 2 + 2))
            pebbleUpdate[destKey] = times[i].shortDescription
            pebbleUpdate[timeKey] = NSNumber(int32: Int32(times[i].time.timeIntervalSince1970))
        self.watch?.appMessagesPushUpdate(pebbleUpdate, withUUID: appUUID, onSent: { (w, Dict, e) in
            if let error = e {
                println("Error sending update to pebble: \(error.localizedDescription)")
            } else {
                println("Sent update to pebble!")

There was a problem though: the Pebble showed around -470 minutes for each train (i.e. 8 hours out – suspicious, as local time is +8:00). Turns out Pebble has no concept of timezone at all. The docs spin this as: “Note that the epoch is adjusted for Timezones and Daylight Savings.” Not sure that qualifies as epoch time, but it was clear the conversion is meant to happen on the phone. The following code sorted the issue:

  let adjustedEpoch = Int(times[i].time.timeIntervalSince1970) + NSTimeZone.localTimeZone().secondsFromGMT
  pebbleUpdate[timeKey] = NSNumber(int32: Int32(adjustedEpoch))

Glorious 1 bit UI

The result (I have a promising future as a watch model). I’ll give it a good workout near the train station over the next week.

Pebble Running

As always, the code is available here, here and here.

A last note: The fact that I’m on week 5 of my watch app development journey and am yet to touch WatchKit is not lost on me. I should hopefully start hitting WatchKit code this week. With a bit of luck.


The operation couldn’t be completed. (SSErrorDomain error 100.)

If you’re trying to test iOS App Store receipt validation, and you perform a receipt refresh using SKReceiptRefreshRequest, you are almost certainly going to come across the mysterious and enigmatic SSErrorDomain Error 100. There’s not a lot of information on the googles, so here’s what I know/suspect.

As far as I can tell, code 100 is the App Store’s way of telling you “Sorry, I have no receipt for that bundle ID for that user”. That’s unlikely to happen in production unless shenanigans are underway (a receipt is generated even for a free app ‘Get’), but it can happen often in development. The sandbox App Store appears to have the ability to generate fake receipts when requested, but all ducks need to be in a row for this to happen.

In the sandbox (Development/Ad Hoc builds):

  • If you don’t have an app record set up in iTunes Connect, you’ll get a Code 100
  • If you’re signed in with your regular Apple ID instead of a sandbox account: Code 100
  • If you’re signed in with a sandbox account associated with a different iTunes Connect account: Code 100

The story is a bit different for Apple Testflight builds – these are production builds with special handling for in-app purchases, and the App Store (currently) does NOT generate a fake original purchase receipt. I haven’t tested this myself, but from a developer report on the dev forums (login required):

  • If you have a virgin install from TestFlight, you’ll get a Code 100
  • If you’ve previously installed the App Store version of the app, you’ll get a receipt
  • If you have a virgin install from TestFlight but have made an in-app purchase, you’ll get a receipt

Hopefully this saves others some frustration.