比较 NSTextRange 是否相等

问题描述 投票:0回答:1

给定两个带有自定义 NSTextLocation 的 NSTextRange,我们如何比较它们是否相等?

class Location: NSObject, NSTextLocation {
    let value: Int

    func compare(_ location: NSTextLocation) -> ComparisonResult {
        guard let location = location as? Location else {
            fatalError("Expected Location")
        }

        if self.value == location.value {
            return .orderedSame
        } else if self.value < location.value {
            return .orderedAscending
        } else {
            return .orderedDescending
        }
    }

    init(_ value: Int) {
        self.value = value
    }
}

let textRange1 = NSTextRange(location: Location(1), end: Location(2))!
let textRange2 = NSTextRange(location: Location(1), end: Location(2))!

print("startLocations are equal: \(textRange1.location.compare(textRange2.location) == .orderedSame)")
print("endLocations are equal: \(textRange1.endLocation.compare(textRange2.endLocation) == .orderedSame)")
print("ranges are equal: \(textRange1.isEqual(to: textRange2))")

在上面的示例中,两个 NSTextRanges 的起始位置和结束位置比较为

.orderedSame
。但是,与两个范围的相等性比较失败。我本以为他们是平等的。

我们如何比较它们是否相等?

cocoa textkit
1个回答
0
投票

textRange1.isEqual(to: textRange2)
textRange1.location.isEqual(to: textRange2.location)
textRange1.endLocation.isEqual(to: textRange2.endLocation)

isEqual(_:)
NSObjectProtocol
的方法,由
NSTextLocation
继承。在
Location
中实现它,使
textRange1.isEqual(to: textRange2)
工作。

override func isEqual(_ object: Any?) -> Bool {
    guard let location = object as? Location else {
        fatalError("Expected Location")
    }
    return self.value == location.value
}
© www.soinside.com 2019 - 2024. All rights reserved.