Skip to content

Instantly share code, notes, and snippets.

@carlhunterroach
Forked from jesskturner/string-truncate.swift
Last active May 21, 2016 00:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save carlhunterroach/445e47525779ec634e9e to your computer and use it in GitHub Desktop.
Save carlhunterroach/445e47525779ec634e9e 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 = "") -> 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) // "This is a …"
@carlhunterroach
Copy link
Author

replaced "three dots" ... with ellipsis …
changed the default trailing string to ellipsis
and replaced optional with String so removing nil check

@gkye
Copy link

gkye commented Dec 29, 2015

Thanks

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