Skip to content

Instantly share code, notes, and snippets.

Embed
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 ..."
@burhanaksendir
Copy link

burhanaksendir commented Aug 8, 2015

Thanks for sharing. How you would go about shortening a string without cutting any word off.

say i had the string text = "this is a long string i cant display" i want to trim it down to 10 characters but if it doesnt end with a space finish the word i don't want the string variable to look like this "this is a long string i cant dis" i want it to finish the word until a space occurs.

@jesskturner
Copy link

jesskturner commented Oct 20, 2015

Thanks! I created a fork with this function updated for Swift 2.0: https://gist.github.com/jesskturner/8def9c0cf756b3bbde79

@budidino
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