[swift-evolution] [Pitch] Reducing the bridging magic in dynamic casts

Charles Srstka cocoadev at charlessoft.com
Mon May 2 19:45:42 CDT 2016


> On May 2, 2016, at 4:48 PM, Erica Sadun via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> On May 2, 2016, at 3:45 PM, Chris Lattner via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>> NSError bridging can also be extracted from the runtime, and the same functionality exposed as a factory initializer on NSError:
>>> 
>> 
>> I think that this proposal is overall really great, but what does it do to the “catch let x as NSError” pattern?  What is the replacement?  If the result is ugly, we may have to subset out NSError out of this pass, and handle it specifically with improvements to the error bridging story.
> 
> Grant me the serenity to accept the `NSError` I cannot change and the courage to change the bridging conversions I should. Grant me the wisdom to know the difference between a partial solution that offers a cleaner more predictable interface set now and a full solution that cannot be achieved in a reasonable timeframe.
> 
> -- E

Among the things that Billy Pilgrim could not change were the past, the present, and the future. Hopefully we have better luck, because the ErrorType to NSError bridging is currently a bit buggy.

Have a look at this code, and take a guess at what the results should be:

import Foundation

extension ErrorType {
	public func toNSError() -> NSError {
		return self as NSError
	}
}

let error = NSError(domain: "Foo", code: -1, userInfo: [NSLocalizedFailureReasonErrorKey : "Something went wrong"])

let ns = error.toNSError()

print("Type of error was \(error.dynamicType), type of ns is \(ns.dynamicType)")

print("error's user info: \(error.userInfo)")
print("ns user info: \(ns.userInfo)”)

--

The results are a bit surprising:

Type of error was NSError, type of ns is _SwiftNativeNSError
error's user info: [NSLocalizedFailureReason: Something went wrong]
ns user info: [:]

What happened was:

1. The toNSError() method showed up for our NSError, since NSError is presented to Swift as conforming to ErrorType. 

2. However, due to a lack of dynamism, the code in the extension assumes that we have a Swift native error and *not* an NSError, so it goes ahead and wraps the NSError inside another NSError.

3. And since Swift doesn’t currently do anything to address the userInfo field, the userInfo that our error had gets chopped off.

Whoops.

Charles

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160502/827ec0ae/attachment.html>


More information about the swift-evolution mailing list