-
-
Save budidino/8585eecd55fd4284afaaef762450f98e to your computer and use it in GitHub Desktop.
String truncate extension for Swift 4
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 the specified length number of characters and appends an optional trailing string if longer. | |
- Parameter length: Desired maximum lengths of a string | |
- Parameter trailing: A 'String' that will be appended after the truncation. | |
- Returns: 'String' object. | |
*/ | |
func trunc(length: Int, trailing: String = "…") -> String { | |
return (self.count > length) ? self.prefix(length) + trailing : self | |
} | |
} | |
// Swift 4.0 Example | |
let str = "I might be just a little bit too long".truncate(10) // "I might be…" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A safe version :