Skip to content

Instantly share code, notes, and snippets.

@jesskturner
Forked from aorcsik/string-truncate.swift
Last active March 18, 2018 17:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jesskturner/8def9c0cf756b3bbde79 to your computer and use it in GitHub Desktop.
Save jesskturner/8def9c0cf756b3bbde79 to your computer and use it in GitHub Desktop.
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 ..."
@carlhunterroach
Copy link

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

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