Ask Erica: How do Enums synthesize ErrorType

JSCardwell4: “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.”

I am of course guessing but I suspect there’s a default implementation for ErrorType where Hashable that produces _code; the _domain is just a string of the parent type. If you know better, please give me a heads up.

enum Error : ErrorType {case NoError, Unlucky}

print(Error.NoError._code) // hash value 0
print(Error.Unlucky._code) // hash value 1
print(Error.NoError._domain) // String of Enumeration, "Error"

Comments are closed.