简体   繁体   English

比较Swift String和NSAttributedString

[英]Compare Swift String and NSAttributedString

How can I compare a NSAttributedString and a Swift String such that: 如何比较NSAttributedString和Swift字符串,例如:

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

will compile. 将编译。

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
}

Here is an answer using an extension of NSAttributedString utilizing an equality operator: 这是使用等式运算符的NSAttributedString扩展的答案:

extension NSAttributedString {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM