-
-
Save carlhunterroach/445e47525779ec634e9e to your computer and use it in GitHub Desktop.
A little truncate function extension for the default String type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 …" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
replaced "three dots" ... with ellipsis …
changed the default trailing string to ellipsis
and replaced optional with String so removing nil check