Mismatch of Bridging in Foundation vs Darwin Foundation

(Kaiede) #1

There's some behavior from 4.1 and 3 that seems to have regressed in swift-corelibs-foundation, but not the Darwin version of Foundation.

In particular, if I do this:

let value = NSNumber(value: 0.25) as? Bool

In Swift 4.1, 3.1, and also MacOS X 4.2, this returns nil. IBM-Swift/SwiftyJSON on Linux relies on this behavior to detect JSON types for example.

Unfortunately, with the swift-4.2-RELEASE tag, if I'm using swift-corelibs-foundation, either on MacOS X or Linux, this code always returns false.

There's an underlying bug in the implementation of Bool._conditionallyBridgeFromObjectiveC that I'm attempting to fix (it returns false for 0.25, and true for 1.25, while Darwin). I've got a fix, and I've updated the unit tests, but the issue I'm hitting is that for some reason swift-corelibs-foundation seems to consider that the 'as' cast can never fail.

It obviously could fail in 4.1, so I'm trying to understand what drives the 'as' cast and why it is going through _unconditionallyBridgeFromObjectiveC for NSNumber, instead of _conditionallyBridgeFromObjectiveC like it appeared to do in 4.1 and earlier?

(Kaiede) #2

Okay, so I've clarified some misconceptions I had. It looks like 4.1.3 simply just always fails to convert, forcing you to use .doubleValue or .boolValue to get at the underlying type. When the work in 4.2 to start allowing the casts went in, it looks like for some reason swift-corelibs-foundation will unconditionally bridge, while Darwin's Foundation will use the conditional bridge.

So now I'm curious why the compiler wants to emit an unconditional bridge here instead of conditional bridges, when the conditional bridge still makes sense. Could it be because NSNumber is an actual Objective-C type, and the compiler is aware of that?

(Kaiede) #3

Either way, I've got a PR for the behavior issue in conditional bridging:

And I've opened a bug against the use of unconditional bridging on Linux (when Darwin is using conditional bridging), since that sounds a bit like there's something more fundamental going on which the compiler is also participating in that would be difficult for me to fix in the limited free time I have:


(Tony Parker) #4

Thanks for investigating this @Kaiede!

(Kaiede) #5

No worries. I’m still getting comfortable with the code, but I’ve still got a backlog of fixes to open PRs for across the suite.