[swift-evolution] Amendment to SE-0112: Default values for errorDomain and errorCode

Douglas Gregor dgregor at apple.com
Tue Aug 16 12:27:15 CDT 2016


> On Aug 5, 2016, at 4:32 PM, Charles Srstka via swift-evolution <swift-evolution at swift.org> wrote:
> 
> MOTIVATION:
> 
> SE-0112 includes the CustomNSError protocol, which includes the properties errorDomain, errorCode, and errorUserInfo. These properties can be used to tell Swift how to convert an error to an NSError. However, there are no default implementations for errorDomain and errorCode, and there is no way to access the default values for _domain and _code that Error enums get in Swift. Thus, even if all one wanted to do was to provide a value for NSURLErrorKey, one has to do all this:
> 
> enum MyError: CustomNSError {
> 	case foo(URL)
> 	case bar(URL)
> 	case baz(URL)
> 
> 	static var errorDomain: String {
> 		return “com.MyCompany.MyApp.MyError”
> 	}
> 
> 	var errorCode: Int {
> 		switch self {
> 		case .foo(_):
> 			return 1
> 		case .bar(_):
> 			return 2
> 		case .baz(_):
> 			return 3
> 		}
> 	}
> 
> 	var errorUserInfo: [String : NSObject] {
> 		// construct the actual user info
> 	}
> }
> 
> Notice how far down you have to read before you finally get to the part that constructs the interesting information.
> 
> PROPROSED SOLUTION:
> 
> Add default implementations for all the properties in CustomNSError.
> 
> DETAILED DESIGN:
> 
> The implementations for errorCode and errorDomain will simply provide the default values of _code and _domain already provided by Swift enums. The default implementation for errorUserInfo will simply return an empty dictionary.
> 
> This would allow the above enum to be written simply as:
> 
> enum MyError: CustomNSError {
> 	case foo(URL)
> 	case bar(URL)
> 	case baz(URL)
> 
> 	var errorUserInfo: [String : NSObject] {
> 		// construct the actual user info
> 	}
> }
> 
> and the frameworks would provide something appropriate for the domain and code.

+1, this seems entirely reasonable to me, and probably should have been part of the original SE-0112.

	- Doug



More information about the swift-evolution mailing list