-
-
Save kennyledet/49953151c6c6007b1eb7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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