-
-
Save vicc/0224ab078f76a3af6d79986369d5240b to your computer and use it in GitHub Desktop.
A little truncate function extension for the default String type (Swift 3 Ready)
This file contains 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 the specified length number of characters and appends an optional trailing string if longer. | |
- Parameter length: A `String`. | |
- Parameter trailing: A `String` that will be appended after the truncation. | |
- Returns: A `String` object. | |
*/ | |
func truncate(length: Int, trailing: String = "…") -> String { | |
if self.characters.count > length { | |
return String(self.characters.prefix(length)) + trailing | |
} else { | |
return self | |
} | |
} | |
} | |
// Swift 3.0 Example | |
let str = "This is a long string".truncate(10, trailing: "...") // "This is a ..." |
Nice solution, thanks!
Good job! Thanks for sharing!
Swift 4 version: https://gist.github.com/budidino/8585eecd55fd4284afaaef762450f98e
Thanks for sharing!!!
Awesome! Thanks :-)
return String(self.characters.prefix(length)) + trailing
should be
return String(self.utf8.prefix(length)) + trailing
thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 3 Ready with Proper Documentation Added.