Skip to content

Instantly share code, notes, and snippets.

@russbishop
Last active March 29, 2018 12:45
Show Gist options
  • Save russbishop/a7133d2f582f6bbbb15d to your computer and use it in GitHub Desktop.
Save russbishop/a7133d2f582f6bbbb15d to your computer and use it in GitHub Desktop.
Swift.String truncate
import Foundation
public enum TruncateMode: Int {
case Head = 0
case Middle = 1
case Tail = 2
}
public extension String {
func nilIfEmpty() -> String? {
return self.isEmpty ? nil : self
}
/// Truncates a string to the max length using the specified mode
/// :param: maxLength The maximum length (not including any ellipses)
/// :param: mode The truncation mode; if Middle then ellipses are always added
/// :param: addEllipses If mode is not middle, controls whether ellipses are added to the truncated end of the string
func truncateToLength(maxLength: Int, mode: TruncateMode = TruncateMode.Tail, addEllipses: Bool = false) -> String {
if maxLength <= 0 {
return ""
}
let ellipses = addEllipses || mode == .Middle ? "\u{2026}" : ""
var headIndex = self.startIndex
var tailIndex = self.endIndex
if mode == .Head {
tailIndex = advance(self.endIndex, -maxLength, self.startIndex)
}
else if mode == .Tail {
headIndex = advance(self.startIndex, maxLength, self.endIndex)
}
else {
let tailLength = maxLength / 2
let headLength = maxLength - tailLength
headIndex = advance(self.startIndex, headLength, self.endIndex)
tailIndex = advance(self.endIndex, -tailLength, headIndex)
}
if headIndex == self.startIndex && tailIndex == self.endIndex {
return self
}
return self.substringToIndex(headIndex) + ellipses + self.substringFromIndex(tailIndex)
}
}
@russbishop
Copy link
Author

Second revision owes to kballard for his comments; see his take here https://gist.github.com/kballard/f6844e35755e6a04c8f2

@nitesh-iosdev
Copy link

advance(self.startIndex, headLength, self.endIndex) --> this method is depricated in swift 3 and 4 can you please modify this code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment