Skip to content

Instantly share code, notes, and snippets.

@bananafish911
Created December 23, 2016 16:38
Show Gist options
  • Save bananafish911/2c9161f4b8dea979e3ca0558d4821a4b to your computer and use it in GitHub Desktop.
Save bananafish911/2c9161f4b8dea979e3ca0558d4821a4b to your computer and use it in GitHub Desktop.
/// Truncates String to given langth
///
/// - Parameter length: Result string will be limited to the given number of characters.
/// If length is 0 or less - empty string will be returned
/// - Returns: truncated string.
func truncateToLength(_ length: Int) -> String {
if length <= 0 {
// returns empty string
return ""
} else if length < self.characters.count {
let endIndex = self.index(self.startIndex, offsetBy: length)
let truncatedString = self.substring(to: endIndex)
return truncatedString
} else {
return self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment