Search code examples
swiftnsattributedstringequality

Compare Swift String and NSAttributedString


How can I compare a NSAttributedString and a Swift String such that:

let string = "test string"
let attributedString = NSAttributedString(string: string)
let areStringsEqual = attributedString == string

will compile.


Solution

  • Two ways:

    First

    Change

    attributedString == string
    

    to

    attributedString.string == string
    

    Second

    Add this to your code:

    //for attributed.string == string
    func ==(lhs: NSAttributedString, rhs: String) -> Bool {
        return lhs.string == rhs
    }
    
    //for string == attributed.string
    func ==(lhs: String, rhs: NSAttributedString) -> Bool {
        return lhs = rhs.string
    }