Swift: Dancing the Error Mambo

The Swift Programming Language book writes, “In Swift, errors are represented by values of types conforming to the ErrorType protocol…Swift enumerations that adopt ErrorType automatically have the implementation of their conformance synthesized by the compiler.”

The entire documentation currently in the Standard Library for ErrorType outside the book is this:

Screen Shot 2015-06-21 at 12.47.18 PM

Which, you know, right?

I did finally get non-enum error working. Thought I’d share.

public struct Error: ErrorType {
    // Required but currently undocumented
    public var _domain: String {return "com.sadun"}
    public var _code: Int {return 0}

    // My custom bits
    var reason: String
    var source: String

    // Initializer only requires a reason
    // The working inline macros are courtesy of Mike Ash
    public init(_ reason: String, 
        source: String = __FUNCTION__, 
        file: String = __FILE__, 
        line: Int = __LINE__) {
            self.reason = reason
            self.source = "Thrown in \(source) (File: \(file) Line: \(line))"
    }
}

You implement the _domain and _code properties. Otherwise the rest of the ErrorType is handled for you by default protocol implementations.

Here’s an example of what this error looks like:

Screen Shot 2015-06-21 at 12.51.57 PM

You get more file information (beyond <EXPR>) outside of playgrounds.  Somewhat sadly, in an OCD way, I’m weighing whether to adjust the casing and punctuation to match the results from fatalError():

Screen Shot 2015-06-21 at 12.54.44 PM

I’ve also recently written about asynchronous errors.

2 Comments

  • I really like this model. Nice work.

  • Any idea how the enum cases are accessed to synthesize their ‘_code’ property for objective-c consumption? I fiddled with the current state of reflection and mirrors a few weeks ago to try and create extension defaults for my ‘Enumerable’ protocol so I wouldn’t have to keep adding the property … enum WhatUp: Enumerable { case Nuthin, WholeLottaNuthin; static var all: [Whatup] { return [.Nuthin, .WholeLottaNuthin] } } After reading that the compiler synthesizes the bridged NSError to include a ‘code’ value equal to an enum ErrorType case position, I began wondering if their might be a way to retrieve this kind of thing or if it is some kind of compiler magic with the parsed source code.