Skip to content

Commit

Permalink
Added helper function in NSAttributedString
Browse files Browse the repository at this point in the history
  • Loading branch information
rajdeep committed Jul 17, 2024
1 parent 50d742e commit fe74574
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Proton/Sources/Swift/Helpers/NSAttributedString+Range.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit fe74574

Please sign in to comment.