Skip to content

Instantly share code, notes, and snippets.

@vicc
Forked from jesskturner/string-truncate.swift
Last active May 4, 2020 02:33
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vicc/0224ab078f76a3af6d79986369d5240b to your computer and use it in GitHub Desktop.
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)
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

Good job! Thanks for sharing!

@budidino
Copy link

@loverde-co
Copy link

Thanks for sharing!!!

@haansplosion
Copy link

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

@MrRochito
Copy link

thanks

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