From fe74574a95d75889552fec129421d5ef083f9a32 Mon Sep 17 00:00:00 2001 From: Rajdeep Kwatra Date: Wed, 17 Jul 2024 15:34:12 +1000 Subject: [PATCH] Added helper function in NSAttributedString --- .../Helpers/NSAttributedString+Range.swift | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Proton/Sources/Swift/Helpers/NSAttributedString+Range.swift b/Proton/Sources/Swift/Helpers/NSAttributedString+Range.swift index d42ca3f2..b10bdf96 100644 --- a/Proton/Sources/Swift/Helpers/NSAttributedString+Range.swift +++ b/Proton/Sources/Swift/Helpers/NSAttributedString+Range.swift @@ -173,4 +173,27 @@ public extension NSAttributedString { let range = NSRange(location: searchTextRange.location, length: searchText.count) return range } + + func attributedSubstringOrEmpty(from range: NSRange) -> NSAttributedString { + let clamped = range.clamped(upperBound: length) + return attributedSubstring(from: clamped) + } + + func substringOrEmpty(from range: NSRange) -> String { + let clamped = range.clamped(upperBound: length) + return (string as NSString).substring(with: clamped) + } + + func attributeOrNil(_ key: NSAttributedString.Key, at location: Int) -> Any? { + return attributesOrEmpty(at: location)[key] + } + + func attributesOrEmpty(at location: Int) -> [NSAttributedString.Key: Any] { + guard self.length != 0, location >= 0, location < length else { return [:] } + return attributes(at: location, effectiveRange: nil) + } + + func containsAttribute(_ key: NSAttributedString.Key, at location: Int) -> Bool { + attributesOrEmpty(at: location).keys.contains(key) + } }