Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Vladimir Zhelnov - neatek.pw - Web/iOS dev
- extension String {
- func truncate2(length: Int, wordSeparator: String = " ", trailing: String = "…") -> String {
- if self.characters.count > length {
- let words = self.components(separatedBy: wordSeparator)
- var cumulativeCharacters = 0
- var wordsToInclude:[String] = []
- for word in words {
- cumulativeCharacters += word.lengthOfBytes(using: String.Encoding.utf8) + 1
- if cumulativeCharacters < length {
- wordsToInclude.append(word)
- } else {
- return wordsToInclude.joined(separator: wordSeparator) + trailing
- }
- }
- return self.substring( to: self.index(self.startIndex, offsetBy: length) ) + trailing
- } else {
- return self
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement