Skip to content

Instantly share code, notes, and snippets.

@aorcsik
Last active September 27, 2017 16:22
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aorcsik/c8210a84f163b1b644c0 to your computer and use it in GitHub Desktop.
Save aorcsik/c8210a84f163b1b644c0 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 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 ..."
@jesskturner
Copy link

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

@budidino
Copy link

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