Skip to content

Instantly share code, notes, and snippets.

@idStar
Created December 11, 2016 16:03
Show Gist options
  • Save idStar/e89c1855c46f690328b1b5d993b7e2fe to your computer and use it in GitHub Desktop.
Save idStar/e89c1855c46f690328b1b5d993b7e2fe to your computer and use it in GitHub Desktop.
Swift String extension method to provide you with a truncated version of itself, with optional trailing text
extension String {
// Modified from original: https://techvangelist.net/truncate-a-string-in-swift-2-0/
// We respect max character length requested, even if we allow ellipsis.
func truncated(toMaxLength length: Int, trailing: String? = "...") -> String {
if self.characters.count > length {
let trailingText = trailing ?? ""
let uptoIndex = length - 1 - trailingText.characters.count
return self.substringToIndex(self.startIndex.advancedBy(uptoIndex)) + trailingText
} else {
return self
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment