[swift-evolution] Why is AnyObject's bridging so weird in Swift 3?
jgroff at apple.com
Mon Dec 12 15:09:56 CST 2016
> On Dec 12, 2016, at 12:59 PM, Charles Srstka <cocoadev at charlessoft.com> wrote:
>> On Dec 12, 2016, at 2:46 PM, Joe Groff <jgroff at apple.com <mailto:jgroff at apple.com>> wrote:
>> Everything *can* be bridged to an object as a result of SE-0116 ("id-as-Any"), so there's no longer such a thing as a "non-bridgable value type”.
> Ah, so that arbitrary Swift types can be stashed in Objective-C userInfo dictionaries and the like. Of course. Still wish this could have just happened at the bridge, as part of whatever magic converts Arrays to NSArrays, Dictionaries to NSDictionaries, etc. Oh well.
>> #6 is a bug, since the AnyObject method lookup ought to produce `nil` if the ObjC method isn't implemented on the object.
> Good to know that it’s a bug. Hopefully it’ll get fixed in a future release (or at least warn if the ? isn’t before the parens).
> By the way, while we’re at it, I managed to find a way to get the property version to crash by leaving out some question marks, as well:
> print((s as AnyObject).foo as Any) // fatal error: unexpectedly found nil while unwrapping an Optional value
> Interestingly, it works in the context of string interpolation. 'print("\((s as AnyObject).foo)”)’ prints nil, just like you’d expect. It’s just when you pass it straight to print that the crash happens. Once again, the compiler doesn’t give us any kind of warning about this.
>>> 2. Why is there no obvious way to figure out whether something can actually be an object? The already kind of non-obvious “type(of: s) is AnyObject.Type” trick works to tell you if the thing is already a class, but not if something is bridgeable to a class; using it on a string, for example, returns false. And trying something like “type(of: s as AnyObject) is AnyObject.Type” returns true (?!), so that doesn’t work to detect bridgeable things.
>> What are you trying to do that requires you to know whether something is a class or bridgable to a class (which, as mentioned above, includes everything)?
> The immediate use case? Avoiding the crash on #6. ;-) At least there turned out to be a workaround on that.
> Beyond that? Making the whole thing less head-hurtingly complicated, and avoiding random crashing bugs popping up due to the difficulty of completely reasoning about how the whole thing works. But I was a fan of the lamentably departed SE-0083, so grumble, grumble.
Yeah, it would be nice if we could revisit SE-0083. I think it's still doable in a way that could localize the dynamic bridging complexity to Anys that were sourced from Objective-C.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-evolution