Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A little truncate function extension for the default String type (Swift 3 Ready)
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 ..."
Copy link

vicc commented Oct 13, 2016

Swift 3 Ready with Proper Documentation Added.

Copy link

rlxone commented Apr 3, 2017

Nice solution, thanks!

Copy link

eduardo22i commented Aug 9, 2017

Good job! Thanks for sharing!

Copy link

budidino commented Sep 27, 2017

Copy link

loverde-co commented Oct 31, 2017

Thanks for sharing!!!

Copy link

haansplosion commented Nov 30, 2017

Awesome! Thanks :-)

Copy link

kdeda commented Nov 5, 2018

        return String(self.characters.prefix(length)) + trailing

should be
return String(self.utf8.prefix(length)) + trailing

Copy link

Hacoga commented Jan 30, 2019


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