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 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 ..."
@jesskturner
Copy link
Author

jesskturner commented Oct 20, 2015

Updated for Swift 2.0.

@carlhunterroach
Copy link

carlhunterroach commented Nov 6, 2015

Thanks for the 2.0 version.
Made very small changes https://gist.github.com/carlhunterroach/445e47525779ec634e9e

@vicc
Copy link

vicc commented Oct 13, 2016

Great job! Figured I'd update it for Swift 3.0 and add proper documentation. https://gist.github.com/ViccAlexander/0224ab078f76a3af6d79986369d5240b

@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