Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A little truncate function extension for the default String type
extension String {
/// Truncates the string to length number of characters and
/// appends optional trailing string if longer
func truncate(length: Int, trailing: String? = nil) -> String {
if countElements(self) > length {
return self.substringToIndex(advance(self.startIndex, length)) + (trailing ?? "")
} else {
return self
// Example
let str = "This is a long string".truncate(10, trailing: "...") // "This is a ..."
Copy link

budidino commented Sep 27, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment