Created
December 11, 2016 16:03
-
-
Save idStar/e89c1855c46f690328b1b5d993b7e2fe to your computer and use it in GitHub Desktop.
Swift String extension method to provide you with a truncated version of itself, with optional trailing text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension String { | |
// Modified from original: https://techvangelist.net/truncate-a-string-in-swift-2-0/ | |
// We respect max character length requested, even if we allow ellipsis. | |
func truncated(toMaxLength length: Int, trailing: String? = "...") -> String { | |
if self.characters.count > length { | |
let trailingText = trailing ?? "" | |
let uptoIndex = length - 1 - trailingText.characters.count | |
return self.substringToIndex(self.startIndex.advancedBy(uptoIndex)) + trailingText | |
} else { | |
return self | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment