Search code examples
swiftstringprefixsubstringsuffix

How to I get the first or last few characters of a string in a method chain?


If I use functional-style method chains for string manipulation, I can not use the usual machinery for getting the first or last few characters: I do not have access to a reference to the current string, so I can not compute indices.

Example:

[some, nasty, objects]
    .map( { $0.asHex } )
    .joined()
    .<first 100>
    .uppercased()
    + "..."

for a truncated debug output.

So how to I implement <first 100>, or do I have to break the chain?


Solution

  • I don't know of any API that does this. Fortunately, writing our own is an easy exercise:

    extension String {
        func taking(first: Int) -> String {
            if first <= 0 {
                return ""
            } else if let to = self.index(self.startIndex, 
                                          offsetBy: first, 
                                          limitedBy: self.endIndex) {
                return self.substring(to: to)
            } else {
                return self
            }
        }
    }
    

    Taking from the end is similar.

    Find full code (including variants) and tests here.