Skip to content

Instantly share code, notes, and snippets.

@kennyledet
Forked from aorcsik/string-truncate.swift
Last active August 29, 2015 14:13
Show Gist options
  • Save kennyledet/49953151c6c6007b1eb7 to your computer and use it in GitHub Desktop.
Save kennyledet/49953151c6c6007b1eb7 to your computer and use it in GitHub Desktop.
extension String {
/// Truncates the string to length number of characters and
/// appends optional trailing string if longer
func truncate(length: Int, trailing: String? = nil) -> String {
if countElements(self) > length {
return self.substringToIndex(advance(self.startIndex, length)) + (trailing ?? "")
} else {
return self
}
}
}
// Example
let str = "This is a long string".truncate(10, trailing: "...") // "This is a ..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment