The enumerateAttribute(_:in:options:using:) method of NSAttributedString appears to equate arbitrary instances of type Any. Of course, Any does not conform to Equatable, so that should not be possible.
Question: How does the method compare one instance of Any to another?
Context: In Swift, I am subclassing NSTextStorage, and have need to provide my own implementation of this method in Swift.
Observations:
NSAttributedStringattributes come in key-value pairs, with the keys being instances of typeNSAttributedString.Keyand the values being instances of typeAny?, with each pair being associated with one or more ranges of characters in the string. At least, that is how the data structure appears from the outside; the internal implementation is opaque.- The
enumerateAttributemethod walks through the entire range of anNSAttributedString, effectively identifying each different value corresponding to a specified key, and with the ranges over which that value applies. - The values corresponding to a given key could be of multiple different types.
NSAttributedStringseemingly has no way of knowing what underlying types theAnyvalues might be, and thus seemingly no way of type casting in order to make a comparison of two givenAnyvalues.- Yet, the method somehow is differentiating among ranges of the string based on differences in the
Anyvalues. - Interestingly, the method is able to differentiate between values even when the underlying type does not conform to
Equatable. I take this to be a clue that the method may be using some sort of reflection to perform the comparison. - Even more interesting, the method goes so far as to differentiate between values when the underlying type does conform to
Equatableand the difference between two values is a difference that the specific implementation ofEquatableintentionally ignores. In other words, even ifa == breturns true, if there is a difference in opaque properties of a and b that are ignored by==, the method will treat the values as being different, not the same. - I assume the method bridges to an implementation in ObjC.
As you know, Cocoa is Objective-C, so these are Objective-C NSDictionary objects, not Swift Dictionary objects. So equality comparison between them uses Objective-C
isEqual, not Swift==. We are not bound by Swift strict typing, the Equatable protocol, or anything else from Swift.To illustrate, here's a slow and stupid but effective implementation of style run detection:
That correctly prints:
So since it is always possible to compare the attributes at any index with the attributes at another, it is possible to implement attribute enumeration in Swift. (Whether that's a good idea is another question.)