StringUtil.swift (1180B)
1 // 2 // StringUtil.swift 3 // damus 4 // 5 // Created by Terry Yiu on 6/4/23. 6 // 7 8 import Foundation 9 10 extension String { 11 /// Returns a copy of the String truncated to maxLength and "..." ellipsis appended to the end, 12 /// or if the String does not exceed maxLength, the String itself is returned without truncation or added ellipsis. 13 func truncate(maxLength: Int) -> String { 14 guard count > maxLength else { 15 return self 16 } 17 18 return self[...self.index(self.startIndex, offsetBy: maxLength - 1)] + "..." 19 } 20 } 21 22 extension AttributedString { 23 /// Returns a copy of the AttributedString truncated to maxLength and "..." ellipsis appended to the end, 24 /// or if the AttributedString does not exceed maxLength, nil is returned. 25 func truncateOrNil(maxLength: Int) -> AttributedString? { 26 let nsAttributedString = NSAttributedString(self) 27 if nsAttributedString.length < maxLength { return nil } 28 29 let range = NSRange(location: 0, length: maxLength) 30 let truncatedAttributedString = nsAttributedString.attributedSubstring(from: range) 31 32 return AttributedString(truncatedAttributedString) + "..." 33 } 34 }