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 self.characters.count > length {
return self.substringToIndex(self.startIndex.advancedBy(length)) + (trailing ?? "")
} else {
return self
// Example
let str = "This is a long string".truncate(10, trailing: "...") // "This is a ..."
Copy link

jesskturner commented Oct 20, 2015

Updated for Swift 2.0.

Copy link

carlhunterroach commented Nov 6, 2015

Thanks for the 2.0 version.
Made very small changes

Copy link

vicc commented Oct 13, 2016

Great job! Figured I'd update it for Swift 3.0 and add proper documentation.

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