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

Charles Srstka cocoadev at charlessoft.com
Tue May 3 13:41:18 CDT 2016

> On May 3, 2016, at 11:03 AM, Joe Groff <jgroff at apple.com> wrote:
>> On May 2, 2016, at 5:45 PM, Charles Srstka via swift-evolution <swift-evolution at swift.org> wrote:
>>> 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> 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.
> This is a known bug, not intended behavior. The runtime rewraps NSErrors in a bridging _SwiftNativeNSError when it should just pass them through.
> -Joe

Yes, but it might present an argument in favor of the pitch, since simplifying what “as” means would likely reduce the possibility for bugs like this to crop up.

The difficulty in working around it is also kind of telling. You’d expect to be able to just do this:

if let err = self as? NSError {
	return err

but of course the “as?” is going to invoke the bridging mechanism rather than what you wanted, which is just telling you what the thing is. Trying “if self is NSError” doesn’t work either, since the “is” check comes out to be always true due to the bridging mechanism. When I was playing around with this, the only way I could find to just do a plain old type-check without bridging something was to kludge around it using a mirror and unsafeBitCast:

extension ErrorType {
    public func toNSError() -> NSError {
        // NOPE!!! -- for var mirror: Mirror? = Mirror(reflecting: self); mirror != nil; mirror = mirror?.superclassMirror() {
        var argh: Mirror? = Mirror(reflecting: self)
        while let mirror = argh {
            if mirror.subjectType == NSError.self {
                return unsafeBitCast(self, NSError.self)
            argh = mirror.superclassMirror()
        return self as NSError

Now, isn’t that code beautiful? Truly a work of art.

Anyway, the point is that with a simpler type-checking system, we could avoid complications like this.

As an aside, I wonder if NSError could be bridged by doing something similar to how other core Foundation types like NSString and NSArray are bridged. How would it be if:

1. ErrorProtocol has public, non-underscored methods for domain, code, and userInfo, the last of these having a default implementation that just returns an empty dictionary.

2. NSError no longer conforms to ErrorProtocol.

3. A new private error value type is introduced that does conform to ErrorProtocol, probably called something like _ObjCErrorType. This type wraps an NSError, and forwards its domain, code, and userInfo properties to it.

4. There is a subclass of NSError that wraps a native Swift error and forwards the domain, code, and userInfo properties. This already exists in _SwiftNativeNSError, except this would now forward userInfo as well.

5. Objective-C APIs that return NSError object present it as ErrorProtocol in the signature. If the NSError is a _SwiftNativeNSError, the original Swift error is unwrapped and returned. Otherwise, the NSError is wrapped in an instance of _ObjCErrorType and returned as an ErrorProtocol, and the user can access its domain, code, and userInfo through the three methods in the protocol.

6. Objective-C APIs that take NSError objects now show ErrorProtocol in their signatures as well. If an _ObjCErrorType is passed to one of these APIs, its wrapped NSError is unwrapped and passed to the API; otherwise, the error is wrapped in a _SwiftNativeNSError and passed through to the API.

7. For manually bridging from one side to the other, NSError would get an initializer in an extension that would take a Swift error and result in a bridged error. It would also get a swiftNativeError() method that would return an ErrorProtocol.

On the downside, special casing is still needed in steps 5 and 6 to distinguish between wrapped and unwrapped errors. On the upside:

a) This is very similar to the bridging that already exists for String<->NSString, Array<->NSArray, when crossing the language boundary.

b) The special casing would be mostly restricted to the special magic that the compiler inserts when crossing the boundary.

c) As NSError would no longer be an ErrorProtocol, shenanigans related to not knowing whether an ErrorProtocol was native or not, as in the above example, would never happen.

d) Since the is, as, as?, and as! operators would no longer be need to bridge NSErrors to native errors and back, the pitch here becomes viable, and these operators can be made to no longer act in often surprising and confusing ways.

e) The programmer would never have to deal with NSError objects again.

What think you?


More information about the swift-evolution mailing list