Skip to content

Instantly share code, notes, and snippets.

@nitesh-iosdev
Forked from jesskturner/string-truncate.swift
Created March 18, 2018 17:37
Show Gist options
  • Save nitesh-iosdev/f362a64ad97fa6704f3ae4b823f80ec4 to your computer and use it in GitHub Desktop.
Save nitesh-iosdev/f362a64ad97fa6704f3ae4b823f80ec4 to your computer and use it in GitHub Desktop.
A little truncate function extension for the default String type
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 self.characters.count > length {
return self.substringToIndex(self.startIndex.advancedBy(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