[3.0] [AnyHashable] Handle comparisons/casting for wrappers around bridged types #4953
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Swift value types are their bridged Objective-C classes can have
different hash values. To address this, AnyHashable's responds to the
_HasCustomAnyHashableRepresentation protocol, which bridge objects of
those class types---NSString, NSNumber, etc---into their Swift
counterparts. That way, we get consistent (Swift) hashing behavior
across platforms.
However, there are cases where multiple Swift value types map to the
same Objective-C class type. In such cases, AnyHashable ends up
converting the object of class type back to some canonical type. For
example, an NS_STRING_ENUM (such as (NS)RunLoopMode) is a Swift
wrapper around a String. If an (NS)RunLoopMode is placed into an
AnyHashable, it maintains it's Swift type identity (which is correct
behavior). If it is bridged to Objective-C, it becomes an NSString; if
that NSString is placed into an AnyHashable, it produces a String. The
hash values still line up, but equality of the AnyHashable values
fails, which breaks when (for example) a dictionary with AnyHashable
keys is used from Objective-C. See SR-2648 / rdar://problem/27992351
for a case where this breaks interoperability.
To address this problem, make AnyHashable's casting and equality
sensitive to the origin of the hashed value: if the AnyHashable was
created through a _HasCustomAnyHashableRepresentation conformance,
treat comparisons/casting from it as "fuzzy":
representation (e.g., it originated with an Objective-C type like
NSString) but the other did not, bridge the value of the other
AnyHashable to Objective-C, re-wrap it in an AnyHashable, and
compare that. This allows, e.g., an (NS)RunLoopMode created in Swift
to compare to an NSString constant with the same string value.
custom representation and the cast would fail, bridge to Objective-C
and then initiate the cast again. This allows an NSString to be
casted to (NS)RunLoopMode.
Resolves SR-2648 / rdar://problem/27992351.
(cherry picked from commit 6f34118)