How does `NSAttibutedString` equate attribute values of type `Any`?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-1















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:





  • NSAttributedString attributes come in key-value pairs, with the keys being instances of type NSAttributedString.Key and the values being instances of type Any?, 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 enumerateAttribute method walks through the entire range of an NSAttributedString, 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.


  • NSAttributedString seemingly has no way of knowing what underlying types the Any values might be, and thus seemingly no way of type casting in order to make a comparison of two given Any values.

  • Yet, the method somehow is differentiating among ranges of the string based on differences in the Any values.

  • 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 Equatable and the difference between two values is a difference that the specific implementation of Equatable intentionally ignores. In other words, even if a == b returns 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.


Is the answer: It cannot be done in Swift?










share|improve this question























  • There's nothing magic about it. Each keys expect value of a certain type (NSAttributedString.Key.font expects a UIFont, .foregroundColor expects a UIColor, etc.). You can find that by digging into the documentation so you just cast Any to the corresponding type.

    – Code Different
    Nov 22 '18 at 4:54











  • What do you mean "it cannot be done in Swift"? What cannot be done? You can certainly call enumerateAttribute and it works fine, so what exactly is the problem here? "I am subclassing NSTextStorage, and have need to provide my own implementation of this method" Why would you need to override this method?

    – matt
    Nov 22 '18 at 5:06




















-1















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:





  • NSAttributedString attributes come in key-value pairs, with the keys being instances of type NSAttributedString.Key and the values being instances of type Any?, 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 enumerateAttribute method walks through the entire range of an NSAttributedString, 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.


  • NSAttributedString seemingly has no way of knowing what underlying types the Any values might be, and thus seemingly no way of type casting in order to make a comparison of two given Any values.

  • Yet, the method somehow is differentiating among ranges of the string based on differences in the Any values.

  • 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 Equatable and the difference between two values is a difference that the specific implementation of Equatable intentionally ignores. In other words, even if a == b returns 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.


Is the answer: It cannot be done in Swift?










share|improve this question























  • There's nothing magic about it. Each keys expect value of a certain type (NSAttributedString.Key.font expects a UIFont, .foregroundColor expects a UIColor, etc.). You can find that by digging into the documentation so you just cast Any to the corresponding type.

    – Code Different
    Nov 22 '18 at 4:54











  • What do you mean "it cannot be done in Swift"? What cannot be done? You can certainly call enumerateAttribute and it works fine, so what exactly is the problem here? "I am subclassing NSTextStorage, and have need to provide my own implementation of this method" Why would you need to override this method?

    – matt
    Nov 22 '18 at 5:06
















-1












-1








-1








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:





  • NSAttributedString attributes come in key-value pairs, with the keys being instances of type NSAttributedString.Key and the values being instances of type Any?, 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 enumerateAttribute method walks through the entire range of an NSAttributedString, 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.


  • NSAttributedString seemingly has no way of knowing what underlying types the Any values might be, and thus seemingly no way of type casting in order to make a comparison of two given Any values.

  • Yet, the method somehow is differentiating among ranges of the string based on differences in the Any values.

  • 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 Equatable and the difference between two values is a difference that the specific implementation of Equatable intentionally ignores. In other words, even if a == b returns 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.


Is the answer: It cannot be done in Swift?










share|improve this question














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:





  • NSAttributedString attributes come in key-value pairs, with the keys being instances of type NSAttributedString.Key and the values being instances of type Any?, 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 enumerateAttribute method walks through the entire range of an NSAttributedString, 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.


  • NSAttributedString seemingly has no way of knowing what underlying types the Any values might be, and thus seemingly no way of type casting in order to make a comparison of two given Any values.

  • Yet, the method somehow is differentiating among ranges of the string based on differences in the Any values.

  • 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 Equatable and the difference between two values is a difference that the specific implementation of Equatable intentionally ignores. In other words, even if a == b returns 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.


Is the answer: It cannot be done in Swift?







swift nsattributedstring any equatable






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 4:15









Matthew RipsMatthew Rips

3615




3615













  • There's nothing magic about it. Each keys expect value of a certain type (NSAttributedString.Key.font expects a UIFont, .foregroundColor expects a UIColor, etc.). You can find that by digging into the documentation so you just cast Any to the corresponding type.

    – Code Different
    Nov 22 '18 at 4:54











  • What do you mean "it cannot be done in Swift"? What cannot be done? You can certainly call enumerateAttribute and it works fine, so what exactly is the problem here? "I am subclassing NSTextStorage, and have need to provide my own implementation of this method" Why would you need to override this method?

    – matt
    Nov 22 '18 at 5:06





















  • There's nothing magic about it. Each keys expect value of a certain type (NSAttributedString.Key.font expects a UIFont, .foregroundColor expects a UIColor, etc.). You can find that by digging into the documentation so you just cast Any to the corresponding type.

    – Code Different
    Nov 22 '18 at 4:54











  • What do you mean "it cannot be done in Swift"? What cannot be done? You can certainly call enumerateAttribute and it works fine, so what exactly is the problem here? "I am subclassing NSTextStorage, and have need to provide my own implementation of this method" Why would you need to override this method?

    – matt
    Nov 22 '18 at 5:06



















There's nothing magic about it. Each keys expect value of a certain type (NSAttributedString.Key.font expects a UIFont, .foregroundColor expects a UIColor, etc.). You can find that by digging into the documentation so you just cast Any to the corresponding type.

– Code Different
Nov 22 '18 at 4:54





There's nothing magic about it. Each keys expect value of a certain type (NSAttributedString.Key.font expects a UIFont, .foregroundColor expects a UIColor, etc.). You can find that by digging into the documentation so you just cast Any to the corresponding type.

– Code Different
Nov 22 '18 at 4:54













What do you mean "it cannot be done in Swift"? What cannot be done? You can certainly call enumerateAttribute and it works fine, so what exactly is the problem here? "I am subclassing NSTextStorage, and have need to provide my own implementation of this method" Why would you need to override this method?

– matt
Nov 22 '18 at 5:06







What do you mean "it cannot be done in Swift"? What cannot be done? You can certainly call enumerateAttribute and it works fine, so what exactly is the problem here? "I am subclassing NSTextStorage, and have need to provide my own implementation of this method" Why would you need to override this method?

– matt
Nov 22 '18 at 5:06














1 Answer
1






active

oldest

votes


















0














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:



let s = NSMutableAttributedString(
string: "howdy", attributes: [.foregroundColor:UIColor.red])
s.addAttributes([.foregroundColor:UIColor.blue],
range: NSRange(location: 2, length: 1))
var lastatt = s.attributes(at: 0, effectiveRange: nil)
for ix in 1..<5 {
let newatt = s.attributes(at:ix, effectiveRange:nil)
if !(newatt as NSDictionary).isEqual(to: lastatt) {
print("style run ended at (ix)")
lastatt = newatt
}
}


That correctly prints:



style run ended at 2
style run ended at 3


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.)






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53423813%2fhow-does-nsattibutedstring-equate-attribute-values-of-type-any%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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:



    let s = NSMutableAttributedString(
    string: "howdy", attributes: [.foregroundColor:UIColor.red])
    s.addAttributes([.foregroundColor:UIColor.blue],
    range: NSRange(location: 2, length: 1))
    var lastatt = s.attributes(at: 0, effectiveRange: nil)
    for ix in 1..<5 {
    let newatt = s.attributes(at:ix, effectiveRange:nil)
    if !(newatt as NSDictionary).isEqual(to: lastatt) {
    print("style run ended at (ix)")
    lastatt = newatt
    }
    }


    That correctly prints:



    style run ended at 2
    style run ended at 3


    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.)






    share|improve this answer




























      0














      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:



      let s = NSMutableAttributedString(
      string: "howdy", attributes: [.foregroundColor:UIColor.red])
      s.addAttributes([.foregroundColor:UIColor.blue],
      range: NSRange(location: 2, length: 1))
      var lastatt = s.attributes(at: 0, effectiveRange: nil)
      for ix in 1..<5 {
      let newatt = s.attributes(at:ix, effectiveRange:nil)
      if !(newatt as NSDictionary).isEqual(to: lastatt) {
      print("style run ended at (ix)")
      lastatt = newatt
      }
      }


      That correctly prints:



      style run ended at 2
      style run ended at 3


      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.)






      share|improve this answer


























        0












        0








        0







        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:



        let s = NSMutableAttributedString(
        string: "howdy", attributes: [.foregroundColor:UIColor.red])
        s.addAttributes([.foregroundColor:UIColor.blue],
        range: NSRange(location: 2, length: 1))
        var lastatt = s.attributes(at: 0, effectiveRange: nil)
        for ix in 1..<5 {
        let newatt = s.attributes(at:ix, effectiveRange:nil)
        if !(newatt as NSDictionary).isEqual(to: lastatt) {
        print("style run ended at (ix)")
        lastatt = newatt
        }
        }


        That correctly prints:



        style run ended at 2
        style run ended at 3


        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.)






        share|improve this answer













        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:



        let s = NSMutableAttributedString(
        string: "howdy", attributes: [.foregroundColor:UIColor.red])
        s.addAttributes([.foregroundColor:UIColor.blue],
        range: NSRange(location: 2, length: 1))
        var lastatt = s.attributes(at: 0, effectiveRange: nil)
        for ix in 1..<5 {
        let newatt = s.attributes(at:ix, effectiveRange:nil)
        if !(newatt as NSDictionary).isEqual(to: lastatt) {
        print("style run ended at (ix)")
        lastatt = newatt
        }
        }


        That correctly prints:



        style run ended at 2
        style run ended at 3


        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.)







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 '18 at 5:22









        mattmatt

        335k47549746




        335k47549746
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53423813%2fhow-does-nsattibutedstring-equate-attribute-values-of-type-any%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Guess what letter conforming each word

            Port of Spain

            Run scheduled task as local user group (not BUILTIN)