Advertisement
neatekFb

Truncate Swift 3 by words or something else

Nov 2nd, 2016
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.88 KB | None | 0 0
  1. // Vladimir Zhelnov - neatek.pw - Web/iOS dev
  2. extension String {
  3.     func truncate2(length: Int, wordSeparator: String = " ", trailing: String = "…") -> String {
  4.         if self.characters.count > length {
  5.             let words = self.components(separatedBy: wordSeparator)
  6.             var cumulativeCharacters = 0
  7.             var wordsToInclude:[String] = []
  8.             for word in words {
  9.                 cumulativeCharacters += word.lengthOfBytes(using: String.Encoding.utf8) + 1
  10.                 if cumulativeCharacters < length {
  11.                     wordsToInclude.append(word)
  12.                 } else {
  13.                     return wordsToInclude.joined(separator: wordSeparator) + trailing
  14.                 }
  15.             }
  16.             return self.substring( to: self.index(self.startIndex, offsetBy: length) ) + trailing
  17.         } else {
  18.             return self
  19.         }
  20.     }
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement