Skip to content

Instantly share code, notes, and snippets.

@danhixon
danhixon / string-truncate.swift
Last active March 6, 2017 22:58 — forked from carlhunterroach/string-truncate.swift
A truncate function extension for the default String type that honors words.
extension String {
/// Truncates the string to length number of characters and
/// doesn't truncate within a word.
/// appends optional trailing string if longer
func truncate(_ length: Int, wordSeparator: String = " ", trailing: String = "…") -> String {
// only truncate if needed
if self.characters.count > length {
// count the trailing characters first
var cumulativeCharacters = trailing.characters.count