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