比较Swift String和NSAttributedString

时间:2018-02-14 16:40:32

标签: swift nsattributedstring equality

如何比较NSAttributedString和Swift String,以便:

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

将编译。

2 个答案:

答案 0 :(得分:2)

两种方式:

<强>第一

更改

attributedString == string

attributedString.string == string

<强>第二

将此添加到您的代码中:

//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
}

答案 1 :(得分:-1)

以下是使用等于运算符的NSAttributedString扩展的答案:

extension NSAttributedString {

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