Last active
March 29, 2018 12:45
-
-
Save russbishop/a7133d2f582f6bbbb15d to your computer and use it in GitHub Desktop.
Swift.String truncate
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
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) | |
} | |
} |
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
Second revision owes to kballard for his comments; see his take here https://gist.github.com/kballard/f6844e35755e6a04c8f2