swift - How to I get the first or last few characters of a string in a method chain? -
if use functional-style method chains string manipulation, can not use usual machinery getting first or last few characters: not have access reference current string, can not compute indices.
example:
[some, nasty, objects] .map( { $0.ashex } ) .joined() .<first 100> .uppercased() + "..."
for truncated debug output.
so how implement <first 100>
, or have break chain?
i don't know of api this. fortunately, writing our own easy exercise:
extension string { func taking(first: int) -> string { if first <= 0 { return "" } else if let = self.index(self.startindex, offsetby: first, limitedby: self.endindex) { return self.substring(to: to) } else { return self } } }
taking end similar.
find full code (including variants) , tests here.
Comments
Post a Comment