Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Swift String extension method to provide you with a truncated version of itself, with optional trailing text
extension String {
// Modified from original:
// 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
You can’t perform that action at this time.