-
-
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…" |
@salva
Something like thisfunc trunc(length: Int, trailing: String = "…") -> String { if (self.count <= length) { return self } var truncated = self.prefix(length) while truncated.last != " " { truncated = truncated.dropLast() } return truncated + trailing }
Works, just needs a guard in case the string has no " " space
func trunc(length: Int, trailing: String = "…") -> String { if (self.count <= length) { return self } var truncated = self.prefix(length) while truncated.last != " " { guard truncated.count > length else { break } truncated = truncated.dropLast() } return truncated + trailing } `
You keep summoning me, so...
If the main use of trunc
is to shorten strings that are too long for presentation purposes, it doesn't make sense to make the replacement when the substitution string is actually longer than the part that is being removed:
A better approach is to let the length
argument mean the new length of the string, with trailing
included:
var truncated = self.prefix(length - trailing.count)
Then you may like to consider the edge case where the length of trailing
is bigger than length
.
A safe version :
extension String {
func trunc(length: Int, trailing: String = "…") -> String {
let maxLength = length - trailing.count
guard maxLength > 0, !self.isEmpty, self.count > length else {
return self
}
return self.prefix(maxLength) + trailing
}
}
Thanks. Have used in my project SpotifyLyricsInMenubar
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice Gist, I would just add taking into account the trailing for the length of the string (I also updated the function signature to work with your example):
Using your example,
let str = "I might be just a little bit too long".truncate(10)
would now return a string with 10 characters (I might…
), instead of 13 like before (I might be…
).