-
-
Save jesskturner/8def9c0cf756b3bbde79 to your computer and use it in GitHub Desktop.
A little truncate function extension for the default String type
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 { | |
/// 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 ..." |
Thanks for the 2.0 version.
Made very small changes https://gist.github.com/carlhunterroach/445e47525779ec634e9e
Great job! Figured I'd update it for Swift 3.0 and add proper documentation. https://gist.github.com/ViccAlexander/0224ab078f76a3af6d79986369d5240b
Swift 4 version: https://gist.github.com/budidino/8585eecd55fd4284afaaef762450f98e
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated for Swift 2.0.