swift4.2nsattributedstringkey

How to check two NSAttributedString.key of a NSAttributed string for equality?


I am implementing a set game where my cards are buttons which consist of NSAttributedString as attributed titles. To check whether three selected cards make a set or not I wanted to compare the attributes on each attributed string (which are attributed titles on the buttons) since each attribute represent a property. This can't be done as I am getting a compilation error while comparing them.

let at: [NSAttributedString.Key : Any] = [
            .strokeColor : UIColor.blue,
            .foregroundColor : UIColor.white,
            .strokeWidth : -7.0,
            .font : UIFont.systemFont(ofSize: 35)
        ]

let s = NSAttributedString(string: "●", attributes: at)
        let attribute: [NSAttributedString.Key : Any] = [
            .strokeColor : UIColor.blue,
            .foregroundColor : UIColor.white,
            .strokeWidth : -7.0,
            .font : UIFont.systemFont(ofSize: 35)
        ]
let a = NSAttributedString(string: "▲", attributes: attribute)

if(s.attributes(at: 0, effectiveRange: nil) & (a.attributes(at: 0, effectiveRange: nil)) // ## Compilation Error: Any doesn't conform to Eqautable Protocol ##

Solution

  • You can use NSAttributedString instance func isEqual(to other: NSAttributedString) -> Bool method for these purpose.