Skip to content

Instantly share code, notes, and snippets.

Embed
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 ..."
@vicc
Copy link
Author

vicc commented Oct 13, 2016

Swift 3 Ready with Proper Documentation Added.

@rlxone
Copy link

rlxone commented Apr 3, 2017

Nice solution, thanks!

@eduardo22i
Copy link

eduardo22i commented Aug 9, 2017

Good job! Thanks for sharing!

@budidino
Copy link

budidino commented Sep 27, 2017

@loverde-co
Copy link

loverde-co commented Oct 31, 2017

Thanks for sharing!!!

@haansplosion
Copy link

haansplosion commented Nov 30, 2017

Awesome! Thanks :-)

@kdeda
Copy link

kdeda commented Nov 5, 2018

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

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

@Hacoga
Copy link

Hacoga commented Jan 30, 2019

thanks

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